One Piece
链接:https://ac.nowcoder.com/acm/contest/908/C
来源:牛客网
题目描述
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的个数,我们很容易想到位运算中的lowbit,lowbit运算是找到当前二进制中最后面的一个一,所以我们只需不断的减去lowbit,直到原数对于零,就可以得到当前数二进制中一的个数。
lowbit运算 lowbit(n)=n&-n;
#include<iostream>
#include<algorithm>
using namespace std;
int main()
{
int T;
cin >> T;
while (T--)
{
int n,ans=0;
cin >> n;
for(int i = n; n; n -= n & -n)
ans++;
cout << ans << endl;
}
return 0;
}