目录/Table of Content
第十九天问:Add Binary
这次,题目会先给出两个只包含1 和 0的整数,然后需要我们把这两个数字以 二进制的方式相加,最后要返回该数字。
大家好,我是一个喜欢研究算法、机械学习和生物计算的小青年,我的CSDN博客是:一骑代码走天涯
如果您喜欢我的笔记,那么请点一下关注、点赞和收藏。如果內容有錯或者有改进的空间,也可以在评论让我知道。😄
题目&示例 (引用自 LeetCode)
Given two binary strings, return their sum (also a binary string).
The input strings are both non-empty and contains only characters1
or0
.
Example 1:
Input: a = “11”, b = “1”
Output: “100”
Example 2:
Input: a = “1010”, b = “1011”
Output: “10101”
Constraints:
- Each string consists only of
'0'
or'1'
characters. 1 <= a.length, b.length <= 10^4
- 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