Bit Manipulation,对于 '1' 位的操作
Last updated
Was this helpful?
Last updated
Was this helpful?
对付 unsigned int 要把判断条件改为 xx != 0 而不是 xx > 0
(n & -n) 是找 n 的 binary 里最右面的 1 所代表的数
n - (n & -n) 效果为减去 n 的二进制表示中最右边为 1 的 bit
n + (n & -n) 就是直接在最低位的 1 上做进位加法。
这题因为是 un-signed int,最高位 = 1 的情况稍微特殊点,把条件改成 != 0 就行了。
另一种做法是这样,会每次移除最末尾的 siginificant digit,直到 n = 0 为止。
注意 shift rst 的顺序,先 shift,再赋值。
12 :..............0000001100
-12 :............11111110100
12 & -12:.....0000000100
另一种思路是基于这个公式:
f[i] = f[i / 2] + i % 2.