[LeetCode]Hamming Distance - python 1 line

来源:互联网 发布:增强手机信号的软件 编辑:程序博客网 时间:2024/06/06 03:38

Hamming Distance(汉明距离)在此问题中,指两个整数转为二进制后,其对应位置上相异字符的个数。如x=1=(0 0 0 1)b, y=4=(0 1 0 0)b,则相异的位置氛围是第二和第四位,即汉明距离为2。
Python一行代码实现如下:

class Solution(object):def hammingDistance(self, x, y):    """    :type x: int    :type y: int    :rtype: int    """    return bin(x^y).count('1')

Runtime: 42ms.

引用评论区Beats 100% Python的solution(非原创):

class Solution(object):
def hammingDistance(self, x, y):
“””
:type x: int
:type y: int
:rtype: int
“””
x = x ^ y
y = 0
while x:
y += 1
x = x & (x - 1)
return y

0 0
原创粉丝点击