两个整数之间的汉明距离指的是这两个数字对应二进制位不同的位置的数目。
给出两个整数 x
和 y
,计算它们之间的汉明距离。
方案一:按为转换成二进制,再用str.count()直接统计1的个数
class Solution(object):
def hammingDistance(self, x, y):
"""
:type x: int
:type y: int
:rtype: int
"""
return bin(x^y).count('1')
方案二:
class Solution(object):
def hammingDistance(self, x, y):
"""
:type x: int
:type y: int
:rtype: int
"""
z = x ^ y
count = 0
while z != 0:
if z & 1 == 1:
count += 1
z = z >> 1
return count