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)
    
  • 相关阅读:
    扩展欧几里得算法
    poj-3094-quicksum
    (floyd)佛洛伊德算法
    poj-3660-cows contest(不懂待定)
    poj-1056-IMMEDIATE DECODABILITY(字典)
    delete与delete[]的区别
    poj-1046-color me less
    SqlParameter 使用
    VS2010中出现无法嵌入互操作类型(转)
    fastreport代码转
  • 原文地址:https://www.cnblogs.com/liuzhanghao/p/14333477.html
Copyright © 2011-2022 走看看