Skip to content

Bit Manipulation

Welcome to the Bit Manipulation section. This module covers everything from reading binary numbers to advanced bitmask techniques that appear in competitive programming and technical interviews.


Bit manipulation is one of those topics that separates candidates who “know DSA” from candidates who truly understand how computers work. Interviewers at FAANG and top-tier companies regularly ask bit manipulation problems because they test:

  • Low-level thinking — do you understand how data is stored?
  • Optimization instinct — can you replace expensive operations with O(1) bit tricks?
  • Pattern recognition — XOR patterns, bitmask DP, subset enumeration
Speed comparison for common operations:
n % 2 === 0 (mod) → check even/odd [slower]
(n & 1) === 0 (bit) → check even/odd [faster, O(1) at hardware level]
Math.floor(n / 2) → divide by 2 [slower]
n >> 1 → divide by 2 [single CPU instruction]

  • Introduction — Binary representation, two’s complement, all 6 bitwise operators with truth tables
  • Bit Tricks — 15+ essential tricks: check even/odd, power of two, get/set/clear/toggle bits, Brian Kernighan’s algorithm
  • XOR Patterns — The XOR identity laws and 7 classic XOR-based problem patterns
  • Practice Problems — 10 fully solved problems: Hamming Weight, Reverse Bits, Counting Bits, Gray Code, UTF-8 Validation, and more
  • Interview Questions — 12+ Q&A covering every trick an interviewer is likely to ask

StepFocusTopic
1UnderstandStart with Introduction — learn the operators
2Memorize TricksStudy Bit Tricks — these recur constantly
3Master XORRead XOR Patterns — XOR is the most interview-tested operator
4Solve ProblemsWork through Practice Problems one by one
5Interview PrepDrill Interview Questions until answers are instant

OPERATOR SYMBOL EXAMPLE RESULT USE CASE
AND & 5 & 3 1 Mask / check bits
OR | 5 | 3 7 Set bits
XOR ^ 5 ^ 3 6 Toggle / find unique
NOT ~ ~5 -6 Complement
Left Shift << 5 << 1 10 Multiply by 2ⁿ
Right Shift >> 5 >> 1 2 Divide by 2ⁿ (signed)
Unsigned >> >>> -1 >>> 0 4294967295 Treat as unsigned 32-bit

TrickCode
Is odd?n & 1
Is power of two?n > 0 && (n & (n-1)) === 0
Get i-th bit(n >> i) & 1
Set i-th bitn | (1 << i)
Clear i-th bitn & ~(1 << i)
Toggle i-th bitn ^ (1 << i)
Clear lowest set bitn & (n - 1)
Isolate lowest set bitn & (-n)
Count set bitsBrian Kernighan’s algorithm
Swap without tempa ^= b; b ^= a; a ^= b

  • Recursion & Backtracking — Subset enumeration via bitmask pairs well with recursive subset generation
  • Arrays — Many bitmask tricks apply directly to array problems
  • Dynamic Programming — Bitmask DP is a powerful technique for state compression