1的个数 【位运算】

问题描述

给定一个十进制整数N,求其对应2进制数中1的个数

Input

第一个整数表示有N组测试数据,其后N行是对应的测试数据,每行为一个整数。

Output

N行,每行输出对应一个输入。

Sample Input

4
2
100
1000
66

Sample Output

1
3
6
2

AC的C++代码:

//适用非负整数
#include<iostream>

using namespace std;

int main()
{
	int n;
	scanf("%d",&n);
	while(n--){
		int x,ans=0;
		scanf("%d",&x);
		while(x>0){
			if(x&1)
			  ans++;
			x>>=1;
		}
		printf("%d\n",ans);
	}
	return 0;
}

猜你喜欢

转载自blog.csdn.net/SongBai1997/article/details/82701402
今日推荐