leetcode 漢明距離 - python3

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

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

注意:
0 ≤ x, y < 231.

 

class Solution:

    def hammingDistance(self, x: int, y: int) -> int:

        x_str = str(bin(x)).replace('0b', '')
        y_str = str(bin(y)).replace('0b', '')

        max_len = max(len(x_str), len(y_str))
        x_str = x_str.zfill(max_len)
        y_str = y_str.zfill(max_len)

        count = 0
        for i in range(max_len):
            if x_str[i] != y_str[i]:
                count += 1
        return count

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章