← Bit Manipulation

Drill #87 — Hamming distance

Easy XOR + Count Bit Manipulation

In plain English: Count how many bits are different between two numbers.

XOR produces 1 at every position where the bits differ โ€” then count the set bits in the XOR result.

Prompt

Find the number of positions at which the corresponding bits of two integers differ.

Try to write it from scratch before scrolling down.

Solution

def hamming_distance(x, y):
    xor = x ^ y  # 1s mark where bits differ
    count = 0
    while xor:
        xor &= xor - 1  # clear lowest set bit
        count += 1
    return count

# Test: hamming_distance(1, 4) == 2  (001 vs 100)
# Test: hamming_distance(3, 1) == 1  (11 vs 01)
O(1) time ยท O(1) space

Related Micro Drills

← Drill #86 Drill #88 →