1. 程式人生 > >leetcode 刷題(python)之漢明距離

leetcode 刷題(python)之漢明距離

兩個整數之間的漢明距離指的是這兩個數字對應二進位制位不同的位置的數目。

給出兩個整數 xy,計算它們之間的漢明距離。

注意:

0 ≤ x, y < 231.

示例:

輸入: x = 1, y = 4

輸出: 2

解釋:

1 (0 0 0 1)

4 (0 1 0 0)

↑ ↑

上面的箭頭指出了對應二進位制位不同的位置。

class Solution:
    def hammingDistance(self, x, y):
        """
        :type x: int
        :type y: int
        :rtype: int
        """
        n = x ^ y # 兩個十進位制數按位異或
        n = bin(n) # 重新複製後的n是一個字串
        print("n type",type(n))
        return n.count('1')