計算一個整數二進位制位中1的個數。要求效率儘可能的高。且能正確求正數和負數的二進位制中1的個數。
阿新 • • 發佈:2018-12-31
#include<iostream>
#include<stdlib.h>
using namespace std;
int Number1(int n)
{
int count = 0;
unsigned int flag = 1;
while (flag)
{
if (flag&n)
count++;
flag = flag << 1;
}
return count;
}
int Number2(int n)
{
int count = 0 ;
while (n)
{
++count;
n = (n - 1)&n;
}
return count;
}
//測試用例的選擇正數的最大值,負數的最大最小值
int main()
{
cout << Number1(0x7fffffff) << endl;
cout << Number1(0x80000000) << endl;
cout << Number1(0xffffffff) << endl;
cout << Number2(0x7fffffff ) << endl;
cout << Number2(0x80000000) << endl;
cout << Number2(0xffffffff) << endl;
system("pause");
return 0;
}