sagelearnai

Bit Manipulation

Signal: "without extra space", "every element appears twice except one", counting set bits, powers of two, subsets as masks, or toggling flags.

Core idea: integers are bit vectors, and bitwise operators process all bits at once in O(1).

OperationExpressionExample (x = 12 = 1100₂)
Test bit i(x >> i) & 1bit 2 → 1
Set bit i`x \(1 << i)`i=0 → 1101
Clear bit ix & ~(1 << i)i=3 → 0100
Clear lowest set bitx & (x − 1)1000
Isolate lowest set bitx & −x0100
Power of two?x > 0 and x & (x − 1) == 0false

XOR superpowers

a ^ a = 0, a ^ 0 = a, and XOR is commutative and associative. So XOR-ing a list where every value appears twice except one cancels the pairs and leaves the single value.

python
def single(nums):
    r = 0
    for x in nums:
        r ^= x
    return r
Language quirks

Python integers are arbitrary precision (there's no 32-bit overflow, and ~x == −x − 1). JavaScript bitwise operators work on 32-bit signed integers, so use >>> 0 to treat a result as unsigned.

Problems

  1. Single Number (Easy): XOR everything; pairs cancel
  2. Number of 1 Bits (Easy): n & (n − 1) clears the lowest set bit
  3. Counting Bits (Easy): bits[i] = bits[i >> 1] + (i & 1)
  4. Reverse Bits (Easy): Shift bits out of n and into the result 32 times
  5. Missing Number (Easy): XOR indices with values (or Gauss sum)
  6. Single Number II (Medium): Count each bit mod 3 (or the ones/twos state machine)
  7. Sum of Two Integers (Medium): sum = a ^ b, carry = (a & b) << 1; repeat until carry is 0 (mask to 32 bits in Python)
  8. Bitwise AND of Numbers Range (Medium): The answer is the common binary prefix of left and right
  9. Power of Two (Easy): n > 0 and n & (n − 1) == 0
  10. Hamming Distance (Easy): popcount(x XOR y)
  11. Add Binary (Easy): Grade-school addition from the right with a carry
  12. Single Number III (Medium): XOR all = a^b; split by its lowest set bit; XOR each group
  13. Gray Code (Medium): g(i) = i ^ (i >> 1), or reflect-and-prefix
  14. Divide Two Integers (Medium): Subtract the largest shifted divisor (doubling) each step; clamp the one overflow case
  15. Reverse Integer (Medium): Pop digits with % and /; return 0 if the result leaves the 32-bit range