[解题笔记] LeetCode 7月挑战题目之5

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

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值