方法一:
思路:如果一个数与1作与运算则可以发现该数最后一位数为1,否则为0.
按照此思路可以有以下代码:
#include <iostream>
using namespace std;
int main()
{
int n = 0;
cout << "输入一个数";
cin >> n;
int count = 0;
while (n)
{
if (n & 1)
{
count++;
}
n >>= 1;
}
cout << "1的个数为"<<count<<endl;
return 0;
}
但是此方法存在缺陷如果输入的数为负数则会无限死循环
方法二:
首先把n与1做与运算,判断n的最低位是不是为1。接着把1左移一位得到2,再和n做与运算,就能判断n的次低位是不是1….这样反复左移,每次能判断n的其中一位是不是1.这个解法中循环的次数等于整数二进制的位数,32位的整数需要循环32次
#include <iostream>
using namespace std;
int main()
{
int n = 0;
int key = 1;
cout << "输入一个数";
cin >> n;
int count = 0;
while (key)
{
if (n & key)
{
count++;
}
key <<= 1;
}
cout << "1的个数为"<<count<<endl;
return 0;
}
结果如上图:
方法三
思路:把一个整数减去1,再和原整数做与运算,会把该整数最右边一个1变成0,那么一个整数的二进制表示中有
多少个1,就可以进行多少次这样的操作。
#include <iostream>
using namespace std;
int main()
{
int n = 0;
cout << "输入一个数";
cin >> n;
int count = 0;
while (n)
{
n = ((n - 1)& n);
count++;
}
cout << "1的个数为"<<count<<endl;
return 0;
}