Hamming Distance
Easy
Topics
The Hamming distance between two integers is the number of positions at which the corresponding bits differ. Given integers a and b, return their Hamming distance.
Example 1
x ^ y — 2.Input: a = 1, b = 4 Output: 2 Explanation: 0001 vs 0100 differ in two bits.
Example 2
Input: a = 3, b = 1 Output: 1
Constraints
- 0 <= a, b <= 2^31 - 1
Editorial — intuition, approach, complexity and pitfalls
Intuition
The Hamming distance counts bit positions where two numbers differ. x XOR y sets exactly those bits — XOR is 1 when its inputs disagree — so the problem reduces to counting the 1-bits of a single number.
Counting set bits can be a loop over all 32 positions, or the faster n & (n-1) trick, which clears the lowest set bit each time and so iterates once per set bit rather than once per position. 💡 Subtracting 1 flips the lowest set bit to 0 and everything below it to 1, so ANDing removes exactly that bit.
Approach
- Compute
x XOR y. - Count its set bits, via a builtin popcount or
while v: v &= v - 1; count += 1.
Dry Run
x = 1, y = 4
1 = 0001
4 = 0100
XOR = 0101 -> two bits set
count with v &= v-1:
v = 0101, v-1 = 0100, AND -> 0100 count 1
v = 0100, v-1 = 0011, AND -> 0000 count 2
v = 0, stop
answer 2Complexity
- Time — O(1): the inputs are fixed-width, so at most 32 iterations, and with the
n & (n-1)trick only as many as there are set bits. - Space — O(1).
Common Pitfalls
- Comparing decimal digits rather than bits.
- Using a signed right shift in a loop over a negative XOR result, which sign-extends and never terminates. Not reachable here since the constraints are non-negative, but it is the classic bug in this family — use an unsigned shift or the
n & (n-1)form. - Reimplementing popcount when the language has one:
Integer.bitCount,__builtin_popcount,bin(v).count("1"). - Assuming both numbers have the same bit length. XOR handles differing magnitudes without alignment work.
Full Solution — all languages
class Solution:
def hammingDistance(self, a, b):
return bin(a ^ b).count('1')import java.util.*;
class Solution {
public int hammingDistance(int a, int b) {
return Integer.bitCount(a ^ b);
}
}#include <bits/stdc++.h>
using namespace std;
class Solution {
public: int hammingDistance(int a, int b) {
return __builtin_popcount((unsigned)(a ^ b));
}
};/**
* @param {number} a
* @param {number} b
* @return {number}
*/ var hammingDistance = function(a, b) {
let x = a ^ b, c = 0;
while (x) {
c += x & 1;
x >>>= 1;
}
return c;
};