L: XueXX and Binary
Description
XueXX is a clever boy. And he always likes numbers in binary(二进制). What an interesting hobby!
Now XueXX has some number in decimal(十进制), he wants to know how many “1”s in a number if the number is written in binary.
Input
The first line of input contains the number of test cases T (T<=100). The descriptions of the test cases follow: The first line of each test case contains one integer a (0
Output
For each test case, output a single line containing the result.
Sample Input
3
1
91
735
Sample Output
1
5
8
这个题目就是输入一个int范围内的数,需要你输出将它转成二进制以后有多少个1
这个题蛮水的,拿出来说一下主要是因为求解过程中那个循环以后还会用到很多次相似的形式,比如快速幂
#include <bits/stdc++.h>
#define N 10100
#define INF 0x3f3f3f3f
#define LL long long
#define mem(a,n) memset(a,n,sizeof(a))
#define fread freopen("in.txt","r",stdin)
#define fwrite freopen("out.txt","w",stdout)
using namespace std;
int main()
{
ios::sync_with_stdio(false);
int n,f,cnt;
cin>>n;
while(n--){
cin>>f;
cnt=0;
while(f){//注意这个循环,以后还会看到长得蛮像的循环
if(f&1){
++cnt;
}
f>>=1;
}
cout<<cnt<<endl;
}
return 0;
}
本文介绍了一个简单的程序设计问题:对于给定的十进制整数,如何计算其二进制表示中1的个数。通过使用位操作,文章提供了一种有效的方法来解决这个问题,并附带了完整的C++代码实现。
464

被折叠的 条评论
为什么被折叠?



