leetcode 461. Hamming Distance(python)

221 阅读1分钟

描述

The Hamming distance between two integers is the number of positions at which the corresponding bits are different.

Given two integers x and y, return the Hamming distance between them.

Example 1:

Input: x = 1, y = 4
Output: 2
Explanation:
1   (0 0 0 1)
4   (0 1 0 0)
       ↑   ↑
The above arrows point to positions where the corresponding bits are different.	

Example 2:

Input: x = 3, y = 1
Output: 1

Note:

0 <= x, y <= 2^31 - 1

解析

根据题意,就是计算汉明距离,两个整数之间的汉明距离是对应二进制位上不同数字的个数。先定义一个函数可以返回一个长度为 32 的表示数字十进制 n 的二进制的结果列表,然后找出变量 x 和 y 两个数字生成的两个列表中,对应索引上数字不相同的个数即可。

解答

class Solution(object):
    def hammingDistance(self, x, y):
        """
        :type x: int
        :type y: int
        :rtype: int
        """
        def b(n):
            r = [0]*32
            i = 0
            while n>0:
                m = n%2
                r[i] = m
                n //= 2
                i+=1
            return r
        x = b(x)
        y = b(y)
        result = 0
        for i in range(32):
            if x[i]!=y[i]:
                result += 1
        return result
        	      
		

运行结果

Runtime: 24 ms, faster than 13.74% of Python online submissions for Hamming Distance.
Memory Usage: 13.4 MB, less than 39.34% of Python online submissions for Hamming Distance.

解析

直接调用内置函数,找出 x 和 y 异或运算后的 1 的个数。

解答

class Solution(object):
    def hammingDistance(self, x, y):
        """
        :type x: int
        :type y: int
        :rtype: int
        """
        return bin(x ^ y).count("1")

运行结果

Runtime: 12 ms, faster than 94.55% of Python online submissions for Hamming Distance.
Memory Usage: 13.5 MB, less than 39.34% of Python online submissions for Hamming Distance.

原题链接:leetcode.com/problems/ha…

您的支持是我最大的动力