Problem Statement
The Hamming distance between two integers is the number of positions at which the corresponding bits are different.
Given two integers x and y, return the Hamming distance between them.
Example:
Input: x = 1, y = 4 Output: 2 Explanation: 1 (in binary: 0001) 4 (in binary: 0100) Bits differ at positions 2 and 3, so distance = 2
Approach 1: XOR + Bit Count
- Use the XOR operation (
^) onxandy.
The XOR of two bits is1if they differ,0if they are the same.
Therefore, the result ofx ^ ywill have1s wherever the bits differ. - Count the number of
1s in the result (that’s the Hamming distance). - There are two ways to count bits:
- Use
Integer.bitCount()in Java. - Or manually count bits using bit shifting.
- Use
Java Solution
public class Solution {
public int hammingDistance(int x, int y) {
int xor = x ^ y; // Step 1: XOR the two numbers
int count = 0;
while (xor != 0) {
count += xor & 1; // Step 2: Add 1 if the last bit is 1
xor >>= 1; // Step 3: Right shift
}
return count;
}
}
Alternative using built-in method:
public int hammingDistance(int x, int y) {
return Integer.bitCount(x ^ y);
}
Complexity Analysis
- Time Complexity: O(1) (since integer size is fixed, usually 32 bits)
- Space Complexity: O(1)
Dry Run
Input: x = 1 (0001), y = 4 (0100)
Step-by-step:
x ^ y = 0001 ^ 0100 = 0101 (binary for 5) count = 0 Iteration 1: xor = 0101 → last bit 1 → count = 1 Iteration 2: xor = 0010 → last bit 0 → count = 1 Iteration 3: xor = 0001 → last bit 1 → count = 2 Iteration 4: xor = 0000 → done Final count = 2
Output: 2
