All Patterns

Bit Manipulation

Use bitwise operators (AND, OR, XOR, shifts, masks) to compute results in constant space and near-constant time.

When to use

  • • XOR to cancel pairs or find a unique element
  • • Bit masks to represent subsets or state
  • • Counting or toggling individual bits
  • • Power-of-two and parity checks

When NOT to use

  • • Logic is clearer with normal arithmetic
  • • Values exceed the integer width you control

Common traps

  • • Signed shifts and the sign bit
  • • Operator precedence of & | ^ versus comparisons
  • • Assuming 32 versus 64-bit width

Key Invariant

XOR cancels equal bits, AND masks them, OR sets them — pick the operator that isolates the bit you care about

Problems (12)

#13Single Number
easyFREE
#59Number of 1 Bits
easy
#164Missing Number
easy
#165Reverse Bits
easy
#168Power of Four
easy
#162Single Number II
medium
#163Single Number III
medium
#166Sum of Two Integers
medium
#167UTF-8 Validation
medium
#297Bitwise AND of Numbers Range
medium
#299Total Hamming Distance
medium
#300Find Longest Substring With Even Vowel Counts
medium