Hamming Distance in Python


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)
    • if b1 = b2, then answer := answer + 0, otherwise answer := answer + 1
  • return answer

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

3K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements