计算二进制位中1的个数

还不理解这个牛逼的算法,怪不得面试的时候会出到这个题:

#define POW(c) (1<<(c))
#define MASK(c) (((unsigned long)-1) / (POW(POW(c)) + 1))
#define ROUND(n, c) (((n) & MASK(c)) + ((n) >> POW(c) & MASK(c)))
int bit_count(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;
}

展开后是这样的:

n = ((n >> 1) & 0x55555555) + (n & 0x55555555);

n = ((n >> 2) & 0x33333333) + (n & 0x33333333);

n = ((n >> 4) & 0x0F0F0F0F) + (n & 0x0F0F0F0F);

n = ((n >> 8) & 0x00FF00FF) + (n & 0x00FF00FF);

n = ((n >> 16) & 0x0000FFFF) + (n & 0x0000FFFF);

点赞