1.题目:实现一个函数,输入一个整数,输出该整数二进制中1 的个数,例如输入7,7的二进制位111,所以输出3.
分析:
传统的方法:使用移位来实现,用数字1与该数字按位与运算,然后逐个向左移位,遍历该数字的每一位,统计出1的个数,按位与的结果是1则证明该位是1,结果是0则证明是0。
另一种方法:先将该数字减一,产生的结果是最右边的1变成0,左边的位不受影响,然后将原数字与相减的结果做与预算,这样可以减少不必要的遍历的次数。
源码:
#include<iostream>
using namespace std;
//======1.最高效的方法=========
int numofOne(int n)
{
int count = 0;
while (n)
{
count++;
n = n&(n - 1);//每次将最右边的1变为0
}
cout << "run for: " << count << " times" << endl;
return count;
}
//======2.常规做法======
int numofOne_2(int n)
{
unsigned int flag = 1;//每次左移一位,按位与
int count = 0;
int times = 0;
while (flag)
{
times++;
if (flag&n)
{
count++;
}
flag = flag << 1;
}
cout << "run for: " << times << " times" << endl;
return count;
}
int main()
{
int number = 0;
cout << "----- first method ------" << endl;
number = numofOne(7);
cout << "the count is: " << number << endl;
cout << "----- second method ------" << endl;
number = numofOne_2(7);
cout << "the count is: " << number << endl;
system("PAUSE");
return 0;
}