3.7.20 · D3Algorithm Paradigms

Worked examples — Bit manipulation — XOR tricks, LSB, counting set bits

2,488 words11 min readBack to topic

The scenario matrix

Before any example, let's list every cell a bit-trick problem can land in. Read this like a checklist — each worked example carries a tag telling you which cell it fills.

Cell Case class What makes it tricky Filled by
A XOR, all-pairs-except-one pairs must be even count Ex 1
B XOR, two unique numbers one XOR pass isn't enough Ex 2
C XOR on the degenerate input (empty / single) limiting behaviour Ex 3
D x & -x on a positive number isolate lowest set bit Ex 4
E x & -x on zero and on a negative (two's complement) sign / degenerate Ex 5
F x & (x-1) power-of-two test, incl. x=0 the false-positive trap Ex 6
G popcount, dense vs sparse which loop wins Ex 7
H word problem (real world) translating words to bits Ex 8
I exam twist: "everything thrice except one" XOR fails, need mod-3 Ex 9

Every symbol used below was defined in the parent: is XOR (bit is 1 when the two bits differ), is the bit at place value , and the LSB is bit (the rightmost switch).


Ex 1 — Cell A: the classic "single number"


Ex 2 — Cell B: TWO numbers appear once (the two-loner twist)


Ex 3 — Cell C: degenerate inputs (empty and single-element)


Ex 4 — Cell D: x & -x on a positive number


Ex 5 — Cell E: x & -x on zero and on a negative


Ex 6 — Cell F: power-of-two test, and the x = 0 trap


Ex 7 — Cell G: popcount, sparse vs dense


Ex 8 — Cell H: real-world word problem


Ex 9 — Cell I: exam twist — XOR fails here


Recall Which cell is my problem?

Everything even except one loner? ::: Cell A — single XOR fold. Two loners? ::: Cell B — XOR all, split on one differing bit with x & -x, XOR two groups. Need the lowest set bit / a splitter mask? ::: x & -x (guard against x == 0). Is x a power of two? ::: x != 0 && (x & (x-1)) == 0 — never forget the x != 0 guard. Everything appears three (odd, >2) times except one? ::: XOR fails — count bits mod 3.

Connections

  • Two's Complement Representation — makes Ex 5's negative x & -x concrete.
  • Hash Sets vs O(1)-space tricks — every example here trades a hash set for space.
  • Bitmask Dynamic Programming — Ex 8's "value as a set of bits" idea generalises.
  • Logarithms and Powers of Two — Ex 6's power-of-two structure.
  • Greedy and Divide-and-Conquer — Ex 2's split-into-two-groups is divide-and-conquer.
  • ← Back to parent topic