题目描述
二进制中1的个数
C++ 代码1
#include <iostream>
using namespace std;
int main()
{
int n;
cin >> n;
while(n--)
{
int temp, total = 0;
scanf("%d",&temp);
while(temp)
{
if(temp & 1) total ++;
temp = temp >> 1;
}
printf("%d ",total);
}
return 0;
}
使用性质
lowbit (num) = num & -num ;
C++ 代码2
#include <iostream>
using namespace std;
int main()
{
int n;
cin >> n;
while(n--)
{
int temp, total;
scanf("%d",&temp);
for(total = 0; temp ; temp -= temp & -temp, total ++);
printf("%d ",total);
}
return 0;
}