Advanced Topic

n & (-n)

n &-n returns the rightmost 1 bit in n., 属于第一次见,很难理解的小trick,这个会在Binary Indexed Tree中用到!

n & (n ^ (n-1)) = n & (-n)

0000 1011 11
1111 0100
1111 0101 -11
0000 0001 11 & (-11)

1010 1000 168
0101 0111 
0101 1000 -168
0000 1000 168 & (-168)
# 充分利用了“取反加一”!

正整数n的二进制表示中,只保留最低位的1的值!

results matching ""

    No results matching ""