The Hamming distance between two integers is the number of positions at which the corresponding bits are different. Given two integers x and y, calculate the Hamming distance. Note: 0 ≤ x, y < 231. Example: Input: x = 1, y = 4 Output: 2 Explanation: 1 (0 0 0 1) 4 (0 1 0 0) ? ? The above arrows point to positions where the corresponding bits are different.
#!/usr/bin/python # -*- coding: UTF-8 -*- class Solution(object): @staticmethod def binaryanumber(self,number): x = 0 for i in range(number): if 2**i > number: return x-1 elif 2**i < number: x += 1 elif 2 ** i == number: return x @staticmethod def getbinarycharlist(self,list): maxbinary = self.binaryanumber(self,list) #最大位数 binarylist = [] binarylist.append(maxbinary) while (list - 2**(maxbinary) != 0): list -= 2**(maxbinary) maxbinary = self.binaryanumber(self,list) binarylist.append(maxbinary) a = binarylist[0]+1 binarylistforAll = [0 for i in range(a)] for i in range(binarylist.__len__()): binarylistforAll[binarylist[i]] = 1 return binarylistforAll def hammingDistance(self,number1,number2): arraya = self.getbinarycharlist(self,number1) arrayb = self.getbinarycharlist(self,number2) x=0 if(arraya.__len__() == arrayb.__len__()): for i in range(arraya.__len__()): if(arraya[i] != arrayb[i]): x += 1 return x else: if (arraya.__len__() > arrayb.__len__()): for i in range(arrayb.__len__()): if (arraya[i] != arrayb[i]): x += 1 if arraya[arraya.__len__()-1] == 1: x +=1 return x else : for i in range(arraya.__len__()): if (arraya[i] != arrayb[i]): x += 1 if arraya[arraya.__len__() - 1] == 1: x += 1 return x Solution = Solution(); print Solution.getbinarycharlista(1,4) ##################################
class Solution(object):
def hammingDistance(self, x, y):
"""
:type x: int
:type y: int
:rtype: int
"""
return bin(x^y).count('1')