zoukankan      html  css  js  c++  java
  • 157-461. 汉明距离

    两个整数之间的汉明距离指的是这两个数字对应二进制位不同的位置的数目。(主题思想就是取异或,之后与1取与)
    class Solution(object):
        def hammingDistance1(self, x, y):
            """
            :type x: int
            :type y: int
            :rtype: int
            """
            binary_ = lambda n: "" if n == 0 else binary_(n // 2) + str(n % 2)
            bin_str_x, bin_str_y = binary_(x), binary_(y)
            max_length = max(len(bin_str_x), len(bin_str_y))
            bin_str_x, bin_str_y = binary_(x).rjust(max_length, "0"), binary_(y).rjust(max_length, "0")
    
            i = 0
            count = 0
            while i < max_length:
                if bin_str_x[i] != bin_str_y[i]:
                    count += 1
                i += 1
            return count
    
        def hammingDistance2(self, x, y):
            """
            :type x: int
            :type y: int
            :rtype: int
            """
            xor = x ^ y
            distance = 0
            while xor:
                if xor & 1:
                    distance += 1
                xor = xor >> 1
            return distance
    
        def hammingDistance3(self, x, y):
            """
            :type x: int
            :type y: int
            :rtype: int
            """
            count = 0
            while x != 0 or y != 0:
                count += (x & 1) ^ (y & 1)
                x >>= 1
                y >>= 1
            return count
    
        def hammingDistance(self, x, y):
            """
            :type x: int
            :type y: int
            :rtype: int
            """
            return bin(x ^ y).count('1')
    
    
    if __name__ == '__main__':
        s1 = Solution()
        x = 1
        y = 4
        root = s1.hammingDistance(x, y)
        print(root)
    
  • 相关阅读:
    2021/4/6
    2021/4/5
    2021/4/2
    2021/4/1
    2021/3/31
    2021/3/30
    2021/3/29重构
    总结
    js 座机正则
    uni-app 条件编译
  • 原文地址:https://www.cnblogs.com/liuzhanghao/p/14333477.html
Copyright © 2011-2022 走看看