求整数的二进制里有多少个1

求整数的二进制里有多少个1https://blog.csdn.net/m0_38121874/article/details/80139608

链接: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.
#include<iostream>
#include<cstdio>
#include<algorithm>
#include<cmath>
#include<string>
#include<cstring>
#include<map>
#include<vector>
#include<set>
#include<list>
#include<stack>
#include<queue>
using namespace std;
typedef long long ll;
int main(){
    int T;
    cin>>T;
    while(T--){
    	int x;
    	cin>>x;
    	int ans=0;
    	while(x){
    		ans++;
    		x=x&(x-1);
		}
		printf("%d\n",ans);
	}
	return 0;
}



 

全部评论

相关推荐

头像
02-15 16:23
中南大学 Java
野猪不是猪🐗:签了美团真是不一样! 亲戚们都知道我签了美团,过年都围着我问送一单多少钱,还让弟弟妹妹们引以为戒,笑我爸我妈养了个🐢孩子,说从小就知道我这个人以后肯定没出息,我被骂的都快上天了
点赞 评论 收藏
分享
秋国🐮🐴:拿到你简历编号然后让你知道世间险恶
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务