← All topics

Bit Manipulation

Masks, shifts, and XOR tricks.

Bit Manipulation

Masks, shifts, and XOR identities.

Core syntax

  • Test bit in & (1 << i).
  • Lowest set bitn & (-n); clear itn & (n - 1).
  • Count bitsn.bit_count() (3.10+) or bin(n).count('1').
missing = 0
for i, x in enumerate(nums):
    missing ^= i ^ x
missing ^= len(nums)          # XOR cancels pairs

Watch out

  • x ^ x == 0 and x ^ 0 == x — the whole trick behind XOR puzzles.
Full cheat sheet →