Finding Hamming Distance

Iqram Ali
Oct 31, 2020

--

Given two integers x, and y return the number of positions where their values differ in their binary representations as a 32-bit integer.

Example 1

Input

x = 9
y = 5

Output

2

9 in binary is 1001 and 5 in binary is 0101, so indices 2 and 3 are different.

class Solution: 
def solve(self, x, y):
ans = 0
while x or y:
ans += (x & 1) ^ (y & 1) x >>= 1 y >>= 1
return ans

Elegant approach:

You can use xor operation, xor’s the given decimal numbers bitwise on their corresponding binary notation.

So, xor of 5 and 9,

5= 01019= 1001 (^)
—-------
1100 =12 in decimal

Now convert the decimal to bin and count the no.of 1’s in the corresponding binary string.

class Solution:
def solve(self, x, y):
a = bin(x ^ y)
return(a.count("1"))

--

--

Iqram Ali

Software Engineering Leader, Product Development, Embedded System Specialist/Mad scientist