Hamming Distance - Problem
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: For x = 1 (binary: 0001) and y = 4 (binary: 0100), the Hamming distance is 2 because bits differ at positions 0 and 2.
Input & Output
Example 1 — Basic Case
$
Input:
x = 1, y = 4
›
Output:
2
💡 Note:
x = 1 (binary: 0001), y = 4 (binary: 0100). Bits differ at positions 0 and 2, so Hamming distance = 2
Example 2 — Same Numbers
$
Input:
x = 3, y = 3
›
Output:
0
💡 Note:
x = 3 (binary: 11), y = 3 (binary: 11). No bits differ, so Hamming distance = 0
Example 3 — Adjacent Numbers
$
Input:
x = 7, y = 8
›
Output:
4
💡 Note:
x = 7 (binary: 0111), y = 8 (binary: 1000). All 4 bit positions differ, so Hamming distance = 4
Constraints
- 0 ≤ x, y ≤ 231 - 1
Visualization
Tap to expand
Understanding the Visualization
1
Input
Two integers x and y to compare
2
Process
XOR the numbers and count set bits
3
Output
Number of positions with different bits
Key Takeaway
🎯 Key Insight: XOR operation naturally identifies all positions where bits differ, making bit counting the core of the solution
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code