//二进制中1的个数
#include<iostream>
using namespace std;
int count_1(int n)
{
int count = 0;
int shift = 1;
for (int i = 0; i < 32; i++)
{
if (n&shift)
count++;
shift = shift << 1;
}
return count;
}
int main()
{
int n;
cin >> n;
cout << count_1(n) << endl;
system("pause");
return 0;
}
我们比较的数字的每一位都和1与运算,然后有 1就计数器增加。