Bit Manipulation: Essential Tricks and Techniques

💡Strategies for Solving This Problem

Understanding Bit Manipulation

Bit manipulation involves directly manipulating bits using bitwise operators. It's crucial for optimization, systems programming, and appears frequently in technical interviews at companies like Google, Facebook, and Microsoft.

Core Bitwise Operators

Operator Symbol Example Result
AND & 5 & 3 1 (0101 & 0011 = 0001)
OR | 5 | 3 7 (0101 | 0011 = 0111)
XOR ^ 5 ^ 3 6 (0101 ^ 0011 = 0110)
NOT ~ ~5 -6 (flip all bits)
Left Shift << 5 << 1 10 (multiply by 2)
Right Shift >> 5 >> 1 2 (divide by 2)

Essential Bit Tricks

1. Check if number is power of 2: n & (n-1) == 0

2. Count set bits: Brian Kernighan's algorithm

3. Get/Set/Clear specific bit:

  • Get ith bit: (n >> i) & 1
  • Set ith bit: n | (1 << i)
  • Clear ith bit: n & ~(1 << i)
  • Toggle ith bit: n ^ (1 << i)

4. XOR properties:

  • a ^ a = 0 (number XOR itself is 0)
  • a ^ 0 = a (number XOR 0 is itself)
  • a ^ b ^ a = b (find unique element)

5. Multiplication/Division by powers of 2:

  • n << k = n * 2^k
  • n >> k = n / 2^k

Common Interview Problems

  • Single Number: Find unique element when all others appear twice
  • Number of 1 Bits: Count set bits (Hamming weight)
  • Reverse Bits: Reverse bit order
  • Power of Two: Check if number is power of 2
  • Sum of Two Integers: Add without + operator
  • Missing Number: Find missing using XOR
  • Bitwise AND of Range: Find AND of all numbers in range

Asked at: Google, Facebook, Amazon, Microsoft, Apple

Scroll to Top