Hamming Distance
Difficulty: Easy · Pattern: Bit Manipulation · LeetCode #461
The Hamming distance between two integers is the number of bit positions in which they differ. Return it for x and y.
Examples
text
x = 1, y = 4 → 2 (0001 vs 0100)
x = 3, y = 1 → 1Hints
- XOR leaves a 1 exactly where the bits differ. Then count the ones.
Approach
z = x ^ y, then count its set bits with Kernighan's trick: while z: z &= z − 1; count += 1. The loop runs once per set bit. Built-ins also work: bin(z).count('1') in Python, or int.bit_count() in 3.10+.
Complexity
Time: O(number of set bits) ≤ 32. Space: O(1).
Python solution
def hammingDistance(x, y):
z, count = x ^ y, 0
while z:
z &= z - 1
count += 1
return countJavaScript solution
function hammingDistance(x, y) {
let z = x ^ y, count = 0;
while (z) { z &= z - 1; count++; }
return count;
}