461. Hamming Distance
class Solution(object):
def hammingDistance(self, x, y):
"""
:type x: int
:type y: int
:rtype: int
"""
x_bin = bin(x).replace('0b','')
y_bin = bin(y).replace('0b','')
if len(x_bin) > len(y_bin):
max_length = len(x_bin)
min_bin = y_bin
max_bin = x_bin
else :
max_length = len(y_bin)
min_bin = x_bin
max_bin = y_bin
#for i in range(max_length - min(len(x_bin), len(y_bin)) ) :
# min_bin = '0' + min_bin
min_bin = '0'*(len(max_bin) - len(min_bin)) + min_bin
count = 0
for i in range(len(max_bin)):
if not min_bin[i] == max_bin[i]:
count += 1
return count
先补全字符串,让两个字符串长度相等,然后每一位比较
149 / 149 test cases passed.
Status: Accepted
Runtime: 39 ms