461. 汉明距离
https://leetcode-cn.com/problems/hamming-distance/
解法一:
每次取x和y的最低位(通过与1‘与’实现)进行异或,用count统计异或为1的次数,然后x和y右移一位,直到相等为止(此时距离为0)。
class Solution:
def hammingDistance(self, x: int, y: int) -> int:
count = 0
while x != y:
count += x&1 ^ y&1
x >>= 1
y >>= 1
return count
解法二:
直接x和y异或,统计结果中1的个数
class Solution:
def hammingDistance(self, x: int, y: int) -> int:
#转二进制字符串,截取数字部分,统计1
return bin(x ^ y)[2:].count('1')
最后更新于