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)
    
  • 相关阅读:
    13.App爬取相关库的安装(Charles,Mitmproxy,Appium)
    26.pymysql、pymongo、redis-py安装
    25.安装配置phantomjs
    2.博客随笔加密!!!
    17.scrapy-splash安装-2
    17.docker及scrapy-splash安装-1
    16.Mongodb安装
    scrapy--BeautifulSoup
    scrapy--selenium
    python--随笔一
  • 原文地址:https://www.cnblogs.com/liuzhanghao/p/14333477.html
Copyright © 2011-2022 走看看