Bit Manipulation
| Trick | Meaning |
|---|---|
x & (x - 1) | clear the lowest set bit (count bits, power-of-two test) |
x & -x | isolate the lowest set bit |
a ^ a = 0, a ^ 0 = a | XOR cancels pairs → find the unique element |
(x >> i) & 1 | read bit i |
x | (1 << i), x & ~(1 << i) | set / clear bit i |
Python caveat: ints are unbounded — emulate 32-bit with & 0xFFFFFFFF and convert back with x if x < 2**31 else x - 2**32.
x = 1 0 1 1 0 0
x - 1 = 1 0 1 0 1 1
x&(x-1) = 1 0 1 0 0 0 lowest 1 removed
Problems
Showing 15 of 15