How can we prove that
i - (i& - i) = i&(i - 1)
mathematically?
Obviously, we can realise that i&(i - 1) unsets the LSB, and (i& - i) gives the LSB (subtracting which, also unsets the LSB). Is there a more concrete backing?
# | User | Rating |
---|---|---|
1 | tourist | 3985 |
2 | jiangly | 3814 |
3 | jqdai0815 | 3682 |
4 | Benq | 3529 |
5 | orzdevinwang | 3526 |
6 | ksun48 | 3517 |
7 | Radewoosh | 3410 |
8 | hos.lyric | 3399 |
9 | ecnerwala | 3392 |
9 | Um_nik | 3392 |
# | User | Contrib. |
---|---|---|
1 | cry | 169 |
2 | maomao90 | 162 |
2 | Um_nik | 162 |
4 | atcoder_official | 161 |
5 | djm03178 | 158 |
6 | -is-this-fft- | 157 |
7 | adamant | 155 |
8 | awoo | 154 |
8 | Dominater069 | 154 |
10 | luogu_official | 150 |
How can we prove that
i - (i& - i) = i&(i - 1)
mathematically?
Obviously, we can realise that i&(i - 1) unsets the LSB, and (i& - i) gives the LSB (subtracting which, also unsets the LSB). Is there a more concrete backing?
Name |
---|
First, the integer i can be expressed in binary as a1b where
a = sequence of 0's and 1's.
1 = the LSB (least-significant bit)
b = sequence of 0's (possibly empty)
Then i - 1 can be expressed as a0bc where bc is the complement of b (a sequence of 1's, possibly empty)
Following this binary representation i & (i - 1) = a1b & a0bc = a
We can apply the same principle to represent i - (i& - i):
- i = ac1b, why? Because - i is the two-complement of i, that is flipping all the bits (one-complement of i) and adding 1
If we apply one-complement to i we get ac0bc, and adding 1 we get ac1b
Now, i & - i = a1b & ac1b = z1b where z is a sequence of zeros with the same length as a
i - (i & - i) = a1b - z1b = a
So, i - (i & - i) = i & (i - 1) = a, (that is, turn off the LSB).
Hope this helps :)
Thanks, sure it helps. :)