1、简单暴力,将每个字符转化为数字后相加
class Solution:
def addBinary(self, a: str, b: str) -> str:
# 思路:如果大于等于2,则进位
i, cur = 0, 0
res = list()
while a or b or cur: # 如果还有字符未存
if a: # 每次存完数字后丢弃
num1 = int(a[-1])
a = a[:-1]
else:
num1 = 0
if b:
num2 = int(b[-1])
b = b[:-1]
else:
num2 = 0
temp = num1 + num2 + cur
if temp <= 1:
res.append(str(temp))
cur = 0
elif temp == 2: # 2,进一
res.append('0')
cur = 1
else: # 3,留一进一
res.append('1')
cur = 1
return ''.join(res[::-1])
2、使用python自带高精度计算
class Solution:
def addBinary(self, a: str, b: str) -> str:
return '{:b}'.format(int(a,2) + int(b,2))
# int(a,2) a为字符串,二进制形式,转化为十进制数字
format: