LeetCode算法題目
題目
兩個整數(shù)之間的漢明距離指的是這兩個數(shù)字對應(yīng)二進(jìn)制位不同的位置的數(shù)目。
給出兩個整數(shù) x 和 y,計算它們之間的漢明距離。
注意:
.
示例 :
輸入: x = 1, y = 4
輸出: 2
解釋:
1 (0 0 0 1)
4 (0 1 0 0)
↑ ↑
上面的箭頭指出了對應(yīng)二進(jìn)制位不同的位置。
解答
Python3
方法一:
class Solution:
def hammingDistance(self, x, y):
"""
:type x: int
:type y: int
:rtype: int
"""
#自定義十進(jìn)制轉(zhuǎn)二進(jìn)制函數(shù)
def dec2bin(num):
num_bin = []
while num!= 0:
num_bin.append(num%2)
num = num // 2
return num_bin[::-1]
x_bin = dec2bin(x)
y_bin = dec2bin(y)
while len(x_bin) != len(y_bin):
if len(x_bin) < len(y_bin):
x_bin.insert(0,0)
else:
y_bin.insert(0,0)
num = 0
for i in range(len(x_bin)):
if x_bin[i] != y_bin[i]:
num += 1
return num
方法二:
class Solution:
def judgeCircle(self, moves):
"""
:type moves: str
:rtype: bool
"""
return list(bin(x^y)).count('1')