1的個數(個人數學見解,非位運算)

 

給定一個十進制整數N,求其對應2進制數中1的個數

Input

第一個整數表示有N組測試數據,其後N行是對應的測試數據,每行爲一個整數。

Output

N行,每行輸出對應一個輸入。

Sample Input

4
2
100
1000
66

Sample Output

1
3
6
2

 

#include<stdio.h>
int main(){
    int n;
	scanf("%d",&n);
	for(int i=0;i<n;i++)
	{
		int x,count=0;
		scanf("%d",&x);
        while(x)
		{
			count+=x%2;  //類似把十進制的每位分開
			x/=2;
		}
		printf("%d\n",count);
	}
	return 0;
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章