思路:先补齐,再相加,有进位则flag变为1
class Solution:
def addBinary(self, a: str, b: str) -> str:
if len(a) < len(b):
a, b = b, a
b = "0" * (len(a) - len(b)) + b
a = list(a)
b = list(b)
flag = [0] * (len(a) + 1)
res = ["0"] * len(a)
for i in range(len(b) - 1, -1, -1):
num = int(a[i]) + int(b[i]) + flag[i]
if num == 0:
pass
elif num == 1:
res[i] = "1"
elif num == 2:
res[i] = "0"
if i > 0:
flag[i - 1] = 1
else:
return "1" + str("".join(res))
else:
res[i] = "1"
if i > 0:
flag[i - 1] = 1
else:
return "1" + str("".join(res))
return "".join(res)