Leetcode:Hamming Distance一些小结

来源:互联网 发布:什么是编程范式 编辑:程序博客网 时间:2024/06/10 12:42

首先,复述一遍题目要求:

The Hamming distance between two integers is the number of positions at which the corresponding bits are different.Given two integers x and y, calculate the Hamming distance.Note:0 ≤ x, y < 2**31.Example:Input: x = 1, y = 4Output: 2Explanation:1   (0 0 0 1)4   (0 1 0 0)       ↑   ↑The above arrows point to positions where the corresponding bits are different.

我是采用python3来求解,在优化算法时,看到了一一个很有趣的解法:

class Solution(object):    def hammingDistance(self, x, y):        """        :type x: int        :type y: int        :rtype: int        """        xor = x ^ y        count = 0        for _ in range(32):            count += xor & 1            xor = xor >> 1        return count

其中,^,&,>>这几个运算符的用法让我耳目一新。参考:http://blog.csdn.net/ialexanderi/article/details/78581621 来进行分析:

x^y将二者二进制转换中,0^1 = 1, 0^0=0, 1^1=0

>>> bin(1)'0b1'>>> bin(4)'0b100'>>> bin(1^4)'0b101'>>> 

这样就可以把相同的位数消除。&将二进制‘1’提出。然后二进制xor<<向左整体移动一位,即xor = xor*2,将提出的位数排除。总计的count就是x,y转换成二进制后相同位数上值不同的数量。

原创粉丝点击