Hamming Distance
这是我第一次参加 LeetCode (力扣) 的每月挑战题组,希望留下点笔记,大家可以参考和互相讨论。😃
第五天问:
两个数字的汉明距离 (Hamming distance) 等于它们俩有多少个不同的二进制位元 (bits) 。
给出任意两个整数 (0
≤
\leq
≤ x, y
<
\lt
< 231),请计算它们的汉明距离。
题目例子 (引用自LeetCode):
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.
解题思路:
这道题其实挺容易,只需要理解编程上的位元运算 (bitwise operation) 概念便能做得出来。这里使用了一个比较 naive 方法:把数字直接变成二进制字串,再用 for-loop 逐一字符对比。
这里用了一个python3 的內置函数 format()
,第一个参数是十进制数字,第二个参数是转换成二进制后需要多少个字符。有兴趣的可以参考文章末后的资料。
代码 (时间复杂度:O(31) = O(1))
class Solution:
def hammingDistance(self, x: int, y: int) -> int:
if x == y:
return 0
x_bin = format(x, '031b')
y_bin = format(y, '031b')
counter = 0
for i in range(len(x_bin)):
if x_bin[i] != y_bin[i]:
counter += 1
return counter
Reference/参考资料:
https://www.w3resource.com/python-exercises/python-basic-exercise-140.php
https://stackoverflow.com/questions/16926130/convert-to-binary-and-keep-leading-zeros-in-python