X与X-1的末尾肯定是不同的,一个是1,另一个是0,进行与运算之后为0,所以可以实现将x最末位置0。
原文中的bitcount函数如下:
/* bitcount: count 1 bits in x */
int bitcount(unsigned x)
{
int b;
for (b = 0; x != 0; x >>= 1)
if (x & 01)
b++;
return b;
}
函数bitcount用来统计其整型参数的值为1的二进制位的个数。
重写bitcount函数如下:
int bitcount(unsigned x)
{
int b;
for (b = 0; x != 0; b++)
x&=(x+1);
return b;
}