Skip to content

461 Hamming Distance

461. Hamming Distance

题目: <https://leetcode.com/problems/hamming-distance/

难度 : Easy

有wikipedia的page:

https://en.wikipedia.org/wiki/Hamming_distance

其实思路还是比较简单的

先用异或,再求hamming weight

For binary strings a and b the Hamming distance is equal to the number of ones (Hamming weight) in a XOR b.

一行无敌

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

AC代码

class Solution(object):
    def hammingDistance(self, x, y):
        """
        :type x: int
        :type y: int
        :rtype: int
        """
        dist = 0
        val = x ^ y

        while val:
            dist += 1
            val &= val - 1

        return dist

我们一直在努力

apachecn/AiLearning

【布客】中文翻译组