Hamming Distance Explained
Problem Statement
Given two integers x and y, compute the Hamming distance, which is the number of positions where their binary representations differ. For example, for x = 1 (binary: 01) and y = 4 (binary: 100), the Hamming distance is 2. This problem tests your ability to use XOR to identify differing bits and count them efficiently.
Example
Input: x = 1, y = 4
Output: 2
Explanation: 1 = 001, 4 = 100. The bits differ at the second and third positions.
Code
Java
Python
JavaScript
public class Solution {
public int hammingDistance(int x, int y) {
int xor = x ^ y;
int count = 0;
while (xor != 0) {
count += xor & 1;
xor >>>= 1;
}
return count;
}
public static void main(String[] args) {
Solution sol = new Solution();
System.out.println(sol.hammingDistance(1, 4)); // 2
}
}
def hamming_distance(x, y):
xor = x ^ y
count = 0
while xor:
count += xor & 1
xor >>= 1
return count
# Example usage
print(hamming_distance(1, 4)) # 2
function hammingDistance(x, y) {
let xor = x ^ y;
let count = 0;
while (xor) {
count += xor & 1;
xor >>>= 1;
}
return count;
}
// Example usage
console.log(hammingDistance(1, 4)); // 2
Explanation
- Compute
x ^ yto get a number where 1 bits indicate positions wherexandydiffer. - Initialize a counter
countto track these 1 bits. - While
xoris non-zero, extract the least significant bit usingxor & 1. - Add it to
countand right-shiftxorto process the next bit. - Return the total
count.
Note
The time complexity is O(1) since we process at most 32 bits. The space complexity is O(1). An alternative approach uses built-in bit-counting functions (e.g.,
Integer.bitCount in Java), but the bitwise method is more explicit and portable.
