Leetcode-Easy 461.Hamming Distance

简介: Leetcode-Easy 461.Hamming Distance
Leetcode-Easy是Leecode难度为"Easy"的解法,由python编码实现。


461.Hamming Distance


  • 描述:

45.png

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


相关文章
|
数据库 C语言
LeetCode 72. Edit Distance
给定两个单词word1和word2,找到将word1转换为word2所需的最小操作数。 您对单词允许以下3个操作: 插入一个字符 删除一个字符 替换一个字符
73 0
LeetCode 72. Edit Distance
Leetcode-Easy 72. Edit Distance
Leetcode-Easy 72. Edit Distance
90 0
Leetcode-Easy 72. Edit Distance
LeetCode之Hamming Distance
LeetCode之Hamming Distance
124 0