1. 程式人生 > >python leetcode461 漢明距離

python leetcode461 漢明距離

one day a cannon or one week five cannons

leetcode 461 hamming distance 

(Source) 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 ≤ xy < 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.

知識點注意:x^y是異或運算,不同為1,相同為0,bin()的結果是01字串,求結果01字串中的'1'字元的個數,就是hamming distance。

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