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
Hamming Distance OverviewInput:x = 1 (binary: 0001)y = 4 (binary: 0100)Process:XOR: 0001 ⊕ 0100 = 0101Count 1s: 2 ones foundOutput:Hamming Distance = 2Binary Representation00010100x = 1y = 4DiffDiffResult: 2 positions differ
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
Asked in
Facebook 15 Google 12
125.0K Views
Medium Frequency
~10 min Avg. Time
3.4K Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen