
Tips for Bit Manipulation:
- Properties of XOR. Problem 136, Problem 268, Problem 389, Problem 421,
x ^ 0 = x
x ^ 11111……1111 = ~x
x ^ (~x) = 11111……1111
x ^ x = 0
a ^ b = c => a ^ c = b => b ^ c = a (commutative law)
a ^ b ^ c = a ^ (b ^ c) = (a ^ b)^ c (associative law)
- Construct a special Mask, setting the special positions to 0 or 1.
1. Clear the rightmost n bits of x, x & ( ~0 << n )
2. Get the value of the nth bit of x (0 or 1), (x >> n) & 1
3. Get the power value of the nth bit of x, x & (1 << (n - 1))
4. Set only the nth bit to 1, x | (1 << n)
5. Set only the nth bit to 0, x & (~(1 << n))
6. Clear bits from the highest bit of x through the nth bit (inclusive), x & ((1 << n) - 1)
7. Clear bits from the nth bit through the 0th bit (inclusive), x & (~((1 << (n + 1)) - 1))
- Bitwise
& operations with special meanings. Problem 260, Problem 201, Problem 318, Problem 371, Problem 397, Problem 461, Problem 693,
X & 1 == 1 determines whether it is odd (even)
X & = (X - 1) clears the lowest set bit (LSB)
X & -X gets the lowest set bit (LSB)
X & ~X = 0
