汉明距离即为二进制中相异位的个数,则测两个数的汉明距离,需先转为二进制,然后使用位运算符“^”(相异为1),最终统计“1”的个数即可。
class Solution:
def hammingDistance(self, x, y):
"""
:type x: int
:type y: int
:rtype: int
"""
return(bin(x^y).count('1'))
- 相关知识点:
o. 位运算符“^”(异或):当两对应的二进位相异时,结果为1
o. 十进制转二进制:bin()