One Piece

链接:https://ac.nowcoder.com/acm/contest/908/C
来源:牛客网
 

时间限制:C/C++ 1秒,其他语言2秒
空间限制:C/C++ 32768K,其他语言65536K
64bit IO Format: %lld

题目描述

Luffy once saw a particularly delicious food, but he didn't have the money, so he asked Nami for money. But we all know that Nami can't easily give money to Luffy. Therefore, Nami decided to take a test of Luffy. If Luffy was right, Nami would give him money, otherwise Luffy would only be hungry. The problem is as follows: Give you an 32-bit integer n and find the number of 1 in the binary representation of the integer.
You are the most trusted friend of Luffy, and he is now asking for help.

输入描述:

There are multiple test cases. The first line of the input contains an integer T(T<=10), indicating the number of test cases. For each test case:

The first line contains an 32-bit integer n(-1e9 <= n <= 1e9)

输出描述:

For each test case output one line containing one integer, indicating the number of  1 in the binary representation of the integer.

示例1

输入

复制

3
1
2
3

输出

复制

1
1
2

说明

The binary of 1 is 01, so the number of 1 is 1, and the binary of  2 is 10, so the number of 1 is 1,The binary of 3 is 11, so the number of 1 is 2.

示例2

输入

复制

1
-1

输出

复制

32

说明

The binary of -1 is 11111111111111111111111111111111, so the number of 1 is 32.

题意:求十进制数对应二进制数中1的个数,负数用补码表示。

#include<iostream>
#include<cstring>
using namespace std;
int main()
{
    int n;
    int a;
    cin>>n;;
    while(n--)
    {
        cin>>a;
        int cnt = 0;
        if(a>0)
        {
            while(a>0)
            {
                if(a&1==1)cnt++;
                a>>=1;
            }
        }else if(a<0)
        {
            int t = -1*a;
            t-=1;
            while(t>0)
            {
                if(t&1==1)cnt++;
                t>>=1;
            }
            cnt = 32-cnt;
        }

        cout<<cnt<<endl;
    }



    return 0;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值