← Interval & Math

Micro-Drill #253 — Hamming distance (count differing bits)

Interval & Math Target: 10s

XOR marks differing bits, then Brian Kernighan's trick counts them in O(k) where k is the number of set bits.

xor = x ^ y
count = 0
while xor:
    xor &= xor - 1  # clear lowest set bit
    count += 1

Type it from memory. Go.

Practice Problems

Related Coding Drills

← Micro #252 Micro #254 →