Leetcode-Easy 461.Hamming Distance

时间:2022-05-08
本文章向大家介绍Leetcode-Easy 461.Hamming Distance,主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。
Leetcode-Easy是Leecode难度为"Easy"的解法,由python编码实现。

461.Hamming Distance

  • 描述:
  • 思路: 首先将通过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')