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.
Hamming 距离是两个整数对应的 位 bit 不相同的数量之和。
给出两个数 x ,y,计算他们之间的 Hamming 距离。
Note:
0 ≤ x, y < 2^31.
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.
思路:将给出两的两个十进制数转换成二进制数,计算他们长度的差值,将长度小的数用 0 补齐,依次比较他们的每一位,每当遇到不相同的位时,计数器+1
class Solution(object):
def hammingDistance(self, x, y):
bin_x = bin(x)[2:]
bin_y = bin(y)[2:]
nums = abs(len(bin_y) - len(bin_x))
if len(bin_x) > len(bin_y):
for i in range(nums):
bin_y = '0' + bin_y
else:
for i in range(nums):
bin_x = '0' + bin_x
# print(bin_x)
# print(bin_y)
count = 0
for i in range(max(len(bin_x), len(bin_y))):
# print(i)
# print(bin_x[-i], bin_y[-i])
if bin_x[i] != bin_y[i]:
count += 1
return count