SDE & MLE Prep

Bit Manipulation

TrickMeaning
x & (x - 1)clear the lowest set bit (count bits, power-of-two test)
x & -xisolate the lowest set bit
a ^ a = 0, a ^ 0 = aXOR cancels pairs → find the unique element
(x >> i) & 1read 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