Hamming Distance

The Hamming distance between two integers is the number of bit positions at which their binary representations differ. Given two integers x and y, return the Hamming distance between them.

30:00

Hamming Distance
easy
Free written solution
Topics
Companies

The Hamming distance between two integers is the number of bit positions at which their binary representations differ. Given two integers x and y, return the Hamming distance between them.

Example 1:
Input: {"x":1,"y":4}
Output: 2
Constraints:
  • 0≤x,y≤231−10 \leq x, y \leq 2^{31} - 1

Test Cases
Input (Stdin)
Expected Output (Stdout)
Execution Result

Run code to see results.

Input
arr ={"x":1,"y":4}

Line up x = 1 and y = 4 bit by bit. The Hamming distance counts the columns where they disagree.

Compare column by column

bit 3 ... bit 0

x=1
0
0
0
1
y=4
0
1
0
0
x^y
·
·
·
·
z
·
·
·
·
3
2
1
0

red ring = bits differ

z: 1s still to count

✓ counted

count (one token per z &= z - 1)

count = 0

Variables
VariableValue
x1
y4
DepthFunction Call
Stack empty
0/8