Brian Kernighan 优化法(快速pop_count)
有关最低位 \(1\) 的操作,算是增进对二进制的理解。。
和 \(\text{lowbit}\) 好像,不要搞混。
先上代码(DS版):
int popcount(uint32_t x) {
int count = 0;
while (x) {
x &= x - 1; // 清除最低位的1
count++;
}
return count;
}
对比 \(\text{lowbit}\):
int popcount(uint32_t x) {
int count = 0;
while (x) {
x -= x & -x; // 等价于 x = x & (x - 1)
count++;
}
return count;
}
-
前者:
建议读者手搓数据 \(x-1\)感受二进制减 \(1\) 是怎么一回事。可以发现它无关最后一个 \(1\) 前面的所有位,由此与运算水到渠成,用于消去 \(x\) 末尾的 \(1\)。
如:
$101100 \rightarrow $
\(101011\) -
后者:
lowbit(n)=n&(~n+1)=n&(-n),其中 \(~n\) 是取反操作。
同样如:
$101100 \rightarrow $
\(010011\),再加 \(1\),可以看到前后者的联系了吗?

浙公网安备 33010602011771号