题目
两个整数之间的汉明距离指的是这两个数字对应二进制位不同的位置的数目。
给出两个整数 x 和 y,计算它们之间的汉明距离。
注意:
0 ≤ x, y < 231.
示例:
输入: x = 1, y = 4
输出: 2
解释:
1 (0 0 0 1)
4 (0 1 0 0)
↑ ↑
解法:
用到位运算异或^,二进制展示bin(),和字符串内置函数str.count(str)
代码如下:
class Solution(object):
def hammingDistance(self, x, y):
"""
:type x: int
:type y: int
:rtype: int
"""
print type(bin(x ^ y))
return bin(x ^ y).count("1")
时间复杂度:O(1)
空间复杂度:O(1)
奥利给!
解法二
代码如下:
class Solution(object):
def hammingDistance(self, x, y):
"""
:type x: int
:type y: int
:rtype: int
"""
xor = x ^ y
distance = 0
while xor:
if xor & 1 == 1:
distance += 1
xor = xor >> 1
return distance
奥利给!