class Solution(object):
def hammingDistance(self, x, y):
"""
:type x: int
:type y: int
:rtype: int
"""
x = bin(x)[2:]
y = bin(y)[2:]
if len(x) > len(y):
short, long = y, x
else:
short, long = x, y
while len(short) != len(long):
short = '0' + short
count = 0
for index in range(len(short)):
if short[index] != long[index]:
count += 1
return count
# leetcode 最优解
class Solution2(object):
def hammingDistance(self, x, y):
"""
:type x: int
:type y: int
:rtype: int
"""
return bin(x ^ y).count('1')
网友评论