【Python3】 LeetCode 7月挑战题目之19 - Add Binary

第十九天问:Add Binary

这次,题目会先给出两个只包含10的整数,然后需要我们把这两个数字以 二进制的方式相加,最后要返回该数字。

大家好,我是一个喜欢研究算法、机械学习和生物计算的小青年,我的CSDN博客是:一骑代码走天涯
如果您喜欢我的笔记,那么请点一下关注、点赞和收藏。如果內容有錯或者有改进的空间,也可以在评论让我知道。😄

题目&示例 (引用自 LeetCode)

按此进入题目链结

Given two binary strings, return their sum (also a binary string).
The input strings are both non-empty and contains only characters 1 or 0.

Example 1:

Input: a = “11”, b = “1”
Output: “100”

Example 2:

Input: a = “1010”, b = “1011”
Output: “10101”

Constraints:

  1. Each string consists only of '0' or '1' characters.
  2. 1 <= a.length, b.length <= 10^4
  3. Each string is either "0" or doesn’t contain any leading zero.

解题思路

我的做法思路挺简单,就是纯粹把二进制数换成十进制再相加,加完之后再换回二进制返回函数。

概念是简单,而且不用太多空间需求,但时间复杂度会挺高的。主要是因为int()切割字符串python3中分別是 O( ​ n 2 ​n^2 n2)和 O( ​ n 2 ​n^2 n2),所以时间需求相对的会挺高的。

代码

时间复杂度:O( ​ n 2 ​n^2 n2)
空间复杂度:O( 1 1 1)

class Solution:
    def addBinary(self, a: str, b: str) -> str:
        if a == '0':
            return b
        if b == '0':
            return a
        a = int(a, 2)  #Time complexity = O(n)
        b = int(b, 2)  #Time complexity = O(n)
        res = a + b
        return bin(res)[2:] #Time complexity = O(log n) + O(n^2)

Reference/参考资料

https://stackoverflow.com/questions/50793388/time-complexity-of-bin-in-python
https://stackoverflow.com/questions/44025315/what-is-the-time-complexity-of-int1010-2

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值