两个整数之间的汉明距离指的是这两个数字对应二进制位不同的位置的数目。(主题思想就是取异或,之后与1取与)
class Solution(object):
def hammingDistance1(self, x, y):
"""
:type x: int
:type y: int
:rtype: int
"""
binary_ = lambda n: "" if n == 0 else binary_(n // 2) + str(n % 2)
bin_str_x, bin_str_y = binary_(x), binary_(y)
max_length = max(len(bin_str_x), len(bin_str_y))
bin_str_x, bin_str_y = binary_(x).rjust(max_length, "0"), binary_(y).rjust(max_length, "0")
i = 0
count = 0
while i < max_length:
if bin_str_x[i] != bin_str_y[i]:
count += 1
i += 1
return count
def hammingDistance2(self, x, y):
"""
:type x: int
:type y: int
:rtype: int
"""
xor = x ^ y
distance = 0
while xor:
if xor & 1:
distance += 1
xor = xor >> 1
return distance
def hammingDistance3(self, x, y):
"""
:type x: int
:type y: int
:rtype: int
"""
count = 0
while x != 0 or y != 0:
count += (x & 1) ^ (y & 1)
x >>= 1
y >>= 1
return count
def hammingDistance(self, x, y):
"""
:type x: int
:type y: int
:rtype: int
"""
return bin(x ^ y).count('1')
if __name__ == '__main__':
s1 = Solution()
x = 1
y = 4
root = s1.hammingDistance(x, y)
print(root)