求整数的位模式中包含几个1。
//
//
#include <iostream>
#include <assert.h>
#include <algorithm>
#include <hash_set>
#include <vector>
#include <string>
#include <assert.h>
#include <time.h>
using namespace std;
// O(n)
int bitCount(int x)
{
int sum=0;
while (x)
{
x &= (x-1);
sum++;
}
return sum;
}
// O(logn)
int bitCount2(int x)
{
x=((x&0xAAAAAAAA)>>1)+(x&0x55555555);
x=((x&0xCCCCCCCC)>>2)+(x&0x33333333);
x=((x&0xF0F0F0F0)>>4)+(x&0x0F0F0F0F);
x=((x&0xFF00FF00)>>8)+(x&0x00FF00FF);
return x;
}
int main()
{
int i,x;
time_t ib,ie;
int N=1000;
// bitCount
ib=clock();
while (N--)
{
for (i=0; i<10000; i++)
{
x=bitCount(i);
}
}
ie=clock();
cout<<"bitCount: "<<ie-ib<<" ms"<<endl;
// bitCount2
N=1000;
ib=clock();
while (N--)
{
for (i=0; i<10000; i++)
{
x=bitCount2(i);
}
}
ie=clock();
cout<<"bitCount: "<<ie-ib<<" ms"<<endl;
// check
for (i=0; i<50; i++)
{
cout<<i<<" bitCount(i) = "<<bitCount(i)<<" bitCount2(i) = "<<bitCount2(i)<<endl;
}
return 0;
}
![](https://img-my.csdn.net/uploads/201212/02/1354446547_5305.jpg)