# Hamming Distance in Python

PythonServer Side ProgrammingProgramming

#### Beyond Basic Programming - Intermediate Python

Most Popular

36 Lectures 3 hours

#### Practical Machine Learning using Python

Best Seller

91 Lectures 23.5 hours

#### Practical Data Science using Python

22 Lectures 6 hours

Consider we have two integers. We have to find the Hamming distance of them. The hamming distance is the number of bit different bit count between two numbers. So if the numbers are 7 and 15, they are 0111 and 1111 in binary, here the MSb is different, so the Hamming distance is 1.

To solve this, we will follow these steps −

• For i = 31 down to 0
• b1 = right shift of x (i AND 1 time)
• b2 = right shift of y (i AND 1 time)

## Example

Let us see the following implementation to get a better understanding −

Live Demo

class Solution(object):
def hammingDistance(self, x, y):
"""
:type x: int
:type y: int
:rtype: int
"""
ans = 0
for i in range(31,-1,-1):
b1= x>>i&1
b2 = y>>i&1
ans+= not(b1==b2)
#if not(b1==b2):
# print(b1,b2,i)
return ans
ob1 = Solution()
print(ob1.hammingDistance(7, 15))

## Input

7
15

## Output

1
Updated on 28-Apr-2020 11:05:39