Can anyone help what it n&-nmeans? And what is the significance of this.
n&-n
I believe this is a trick to find out if n is a power of 2. (n == (n and -n)) IFF n is a power of 2 (1,2,4,8).
This is an old trick that gives a number with one bit in it, the bottom bit that was set to n. At least in two arithmetic arithmetic, which today is almost universal.
n
, : , 1 ( ). 1, , , ; , . , , - , - , 1 0.
P.S. , , :
n & (~n + 1)
, , 2, n .
- . .
, , 7 & (-7) x00000111 x11111001 = x00000001 = 1
Mark Randsom .
010010000 | +144 ~ ----------|------- 101101111 | -145 + 1 | ----------|------- 101110000 | -144 101110000 | -144 & 010010000 | +144 ----------|------- 000010000 | 16`
x & -x = {0, 1, 2, 1, 4, 1, 2, 1, 8, 1, 2, 1, 4, 1, 2, 1, 16, 1, 2, 1, 4, 1, 2, 1, 8, 1, 2, 1, 4, 1, 2, 1, 32} x 0 32. . .
x & -x = {0, 1, 2, 1, 4, 1, 2, 1, 8, 1, 2, 1, 4, 1, 2, 1, 16, 1, 2, 1, 4, 1, 2, 1, 8, 1, 2, 1, 4, 1, 2, 1, 32}
x
for(;x < N;x += x&-x) { // do something here ++tr[x]; }
, .
@aestrivex, 1.
for (int y = x; y > 0; y -= y & -y)
and that just means y = y-1, because7 & (- 7) is x00000111 and x11111001 = x00000001 = 1