程序员面试的那些小事程序员Leetcode

Leetcode 461: Hamming Distance

2016-12-22  本文已影响146人  yarving

题目来源

Leetcode 461: Hamming Distance

原题

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 < 231.

Example:

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.

解析

两个整数的海明距离是指其对应二进制不同的位数。如1和4的二进制中有两位不一样,海明距离是2

解答

  1. 两个数做异或操作
  2. 将操作结果转换为str
  3. 遍历str,如果有'1',则距离加1

测试代码

def main():
    def hammingDistance(x, y):
        """
        :type x: int
        :type y: int
        :rtype: int
        """
        res = 0
        for c in str(bin(x ^ y)):
            if c == '1':
                res += 1

        return res

    print hammingDistance(1, 4)

if __name__ == '__main__':
    main()

测试结果

resultresult
上一篇下一篇

猜你喜欢

热点阅读