1. 题目
两个整数之间的汉明距离指的是这两个数字对应二进制位不同的位置的数目。
给出两个整数 x
和 y
,计算它们之间的汉明距离。
注意:
0 ≤ x
, y
< 231.
示例:
输入: x = 1, y = 4 输出: 2 解释: 1 (0 0 0 1) 4 (0 1 0 0) ↑ ↑ 上面的箭头指出了对应二进制位不同的位置。
2. 解答
python3
class Solution(object): def hammingDistance(self, x, y): """ :type x: int :type y: int :rtype: int """ x_two, y_two = [0]*32, [0]*32 while x > 0: cur = int(math.floor(math.log(x, 2))) x_two[cur] = 1 x = x - 2**cur while y > 0: cur = int(math.floor(math.log(y, 2))) y_two[cur] = 1 y = y - 2**cur count = 0 for i in range(len(x_two)): if x_two[i] != y_two[i]: count += 1 return count s = Solution().hammingDistance(1, 4) print(s)