Leetcode-Easy 461.Hamming Distance

Leetcode-Easy是Leecode难度为"Easy"的解法,由python编码实现。

461.Hamming Distance

  • 描述:
Leetcode-Easy 461.Hamming Distance_第1张图片
  • 思路:
    首先将通过bin将x,y转化为二进制字符串,然后逆置,有利于后面字符串比较。用0补齐两个字符串,遍历字符串,比较对应的字符,得出结果。

  • 代码

class Solution(object):
    def hammingDistance(self, x, y):
        """
        :type x: int
        :type y: int
        :rtype: int
        """
        result = 0
        bx = bin(x)[2:][::-1]
        by = bin(y)[2:][::-1]
        if len(bx) <= len(by):
            bx, by = by, bx
        diff = len(bx) - len(by)
        for i in range(diff):
            by += '0'
        for i in range(len(bx)):
            if by[i] != bx[i]:
                result += 1
        return result

另一种方法就是通过x和y的异或运算,统计1的个数。

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

你可能感兴趣的:(Leetcode-Easy 461.Hamming Distance)