0:00 / 0:00

Count the bit positions where two numbers differ: XOR marks every difference, then clear the lowest set bit until none are left.

▼

The problem

LeetCode 461 (Easy). Given two integers x and y, return the Hamming distance between them: the number of bit positions where their binary forms differ.

Examples (LeetCode's): x = 1, y = 4 → 2 (0001 vs 0100) and x = 3, y = 1 → 1 (0011 vs 0001).

TRY IT ON LEETCODE ▶

The solution

def hamming_distance(x, y):
    n = x ^ y
    count = 0
    while n:
        n &= n - 1
        count += 1
    return count

Transcript

Hamming Distance. You're given two integers, x and y. Count the bit positions where their binary forms differ. Think of it as spot the difference, in binary.

Take one and four. One is zero, zero, zero, one. Four is zero, one, zero, zero. They differ in two spots, so the answer is two. Three and one differ in just one spot, so that answer is one.

The slow way turns both numbers into binary strings, pads the shorter one with zeros, and compares them character by character. With thirty-two bit integers it's always thirty-two checks, even when only one bit differs.

The key idea is XOR. For each pair of bits, it gives a one where they disagree, and a zero where they match. So x XOR y is a map of every difference. For one and four, that's zero, one, zero, one: five. Now we just count its ones.

To count them, use Brian Kernighan's trick. Subtract one from n, and its lowest one bit flips to zero, while the zeros below it flip to ones. AND that with n, and only the lowest one bit disappears. So each loop erases exactly one difference. Forty-four has three ones, so it takes three loops. It's Single Number's XOR, followed by Number of One Bits.

In code, n is x XOR y, and the count starts at zero. While n isn't zero, set n to n AND n minus one, and add one to the count. When n hits zero, return the count.

Back to one and four. XOR gives five: zero, one, zero, one. Five AND four is four: the lowest difference is erased, count one. Four AND three is zero: the last one is gone, count two. Nothing is left, so the distance is two.

The loop runs once per differing bit, at most thirty-two times. That's constant time, and constant space: just n and the count.

XOR finds the differences, Kernighan counts them. That's Hamming Distance.