int countones1(unsigned int n)
{
int ones = 0;
while(0 < n)
{
ones += (n & 1);
n >> 1;
}
return ones;
}
复杂度O(logn)
int countones2(unsigned int n)
{
int ones = 0;
while(0 < n)
{
ones++;
n &= n-1;
}
return ones;
}
复杂度O(countOnes(n))
#define POW(c) (1 << (c))
#define MASK(c) (((unsigned int)-1) / (POW(POW(c)) + 1))
#define ROUND(n, c) (((n) & MASK(c)) + (((n) >> POW(c)) & MASK(c)))
int countOnes3(unsigned int n)
{
n = ROUND(n, 0);
n = ROUND(n, 1);
n = ROUND(n, 2);
n = ROUND(n, 3);
n = ROUND(n, 4);
return n;
}
复杂度为O(log2(W)),W=log2(n)为整数的位宽,即为O(loglogn)