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" 思路
这道题和字符串加法思路是一样的,两个字符串都从尾向前遍历,使用溢出标志量进行记录是否存在溢出。直到遍历完毕。时间复杂度为O(n+m), n,m为a,b字符串的长度,空间复杂度为O(N), N为n,m中最大值加1。
解题思路
class Solution(object):
def addBinary(self, a, b):
"""
:type a: str
:type b: str
:rtype: str
"""
res, flow= '', 0 # 设置结果变量和溢出变量
i, j = len(a) - 1, len(b) - 1 # 两个字符串长度
while i >= 0 or j >= 0 or flow: # 循环变量
curval = (i >= 0 and a[i] == '') + (j >= 0 and b[j] == '') # 每一位相加的结果
flow, rem = divmod(curval + flow, 2) # 存储结果
res = `rem` + res
i -= 1
j -= 1
return res