计算一个数字的二进制中1的个数
法一

int main()
{
int n;
cin >> n;
int count = 0;
while (n)
{
if (n & 1 == 1)
{
count++;
}
n = (n >> 1);
}
cout << count << endl;
system("pause");
}

法二 较优解法:

#include<iostream>
using namespace std;
int main()
{
int n;
cin >> n;
int count = 0;
while (n)
{
n = n&(n - 1);
count++;
}
cout << count << endl;
system("pause");
}