求整数的二进制里有多少个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;
}