1的个数
时间限制:
3000 ms | 内存限制:
65535 KB
难度:
1
-
描述
-
小南刚学了二进制,他想知道一个数的二进制表示中有多少个1,你能帮他写一个程序来完成这个任务吗?
-
输入
-
第一行输入一个整数N,表示测试数据的组数(1<N<1000)
每组测试数据只有一行,是一个整数M(0=<M<=10000)
输出
- 每组测试输出占一行,输出M的二进制表示中1的个数 样例输入
-
3 4 6 7
样例输出
-
1 2 3
来源
代码:
#include <iostream> #include <stdio.h> #include <string.h> #include <math.h> #include <vector> #include <queue> #include <stack> #include <map> #include <string> #include <algorithm> using namespace std; /* run this program using the console pauser or add your own getch, system("pause") or input loop */ int main(int argc, char** argv) { int n; scanf("%d",&n); while(n--){ int m; int ans=0; scanf("%d",&m); while(m!=0){ if(m%2 == 1){ ans++; } m/=2; } printf("%d\n",ans); } return 0; }
优秀代码:
1.
#include<stdio.h>
2.
main(){
int
n,m,s;
scanf
(
"%d"
,&n);
while
(n--){
scanf
(
"%d"
,&m);
s=0;
while
(m)
m&=m-1,s++;
printf
(
"%d\n"
,s);
}
}
神奇的优秀代码。
-
第一行输入一个整数N,表示测试数据的组数(1<N<1000)