❤leetcode,python2❤汉明距离

92 阅读1分钟

两个整数之间的汉明距离指的是这两个数字对应二进制位不同的位置的数目。

给出两个整数 x 和 y,计算它们之间的汉明距离。

注意:
0 ≤ x, y < 231.

class Solution(object):
    def hammingDistance(self, x, y):
        """
        :type x: int
        :type y: int
        :rtype: int
        """
        lx = []
        while True:
            x, rx = divmod(x, 2)
            lx.append(rx)
            if x == 0:
                break
        ly = []
        while True:
            y, ry = divmod(y, 2)
            ly.append(ry)
            if y == 0:
                break
        lx.reverse()
        ly.reverse()
        res = 0
        if len(lx) > len(ly):
            ly = [0]*(len(lx)-len(ly))+ly
            for i in range(len(ly)):
                if ly[i] != lx[i]:
                    res += 1
        else:
            lx = [0]*(len(ly)-len(lx))+lx
            for i in range(len(lx)):
                if lx[i] != ly[i]:
                    res+=1
        print res
        return res