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 −
Let us see the following implementation to get a better understanding −
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))