LeetCode 461 Hamming Distance (Python)

Posted by 小明MaxMing on July 5, 2020

题目

The Hamming distance between two integers is the number of positions at which the corresponding bits are different.

Given two integers x and y, calculate the Hamming distance.

解题思路

对两个数求异或,然后求结果的二进制中一共有多少个1

代码

class Solution:
    def hammingDistance(self, x: int, y: int) -> int:
        tmp = x ^ y
        res = 0
        while tmp > 0:
            res += tmp & 1
            tmp >>= 1
        return res
class Solution:
    def hammingDistance(self, x: int, y: int) -> int:
        return bin(x ^ y).count('1')

视频讲解 YouTube<--欢迎点击订阅

视频讲解 bilibili<--欢迎点击订阅