题目描述
给你两个二进制字符串,返回它们的和(用二进制表示)。
输入为 非空 字符串且只包含数字 1 和 0。
示例 1:
提示:
每个字符串仅由字符 ‘0’ 或 ‘1’ 组成。
1 <= a.length, b.length <= 10^4
字符串如果不是 “0” ,就都不含前导零。
解题思路
首先想到的是用竖式相加,但需要处理一个问题就是竖式相加时是低位对齐,而字符串索引是从高位开始索引的,故需要先将字符串翻转,再对短的字符串进行补零(这样在索引时不会越界);翻转后对位相加,再将最后的结果翻转即可得到答案。
1、翻转字符串
2、短的字符串补‘0’
3、对位相加(借助carry位),最后carry位为1,则将carry加至位尾
4、翻转对位相加的结果
代码实现
class Solution:
def addBinary(self, a: str, b: str) -> str:
res_a = a[::-1]
res_b = b[::-1]
la = len(a)
lb = len(b)
n = la
if la > lb: # 补零
n = la
for i in range(la - lb):
res_b += '0'
elif la < lb:
n = lb
for i in range(lb - la):
res_a += '0'
carry = 0
res = ''
for i in range(n): # 遍历对位相加
if carry == 0: # 借助carry位
if res_a[i] == '0' and res_b[i] == '0':
res += '0'
carry = 0
elif (res_a[i] == '0' and res_b[i] == '1')
or (res_a[i] == '1' and res_b[i] == '0'):
res += '1'
carry = 0
else:
res += '0'
carry = 1
else:
if res_a[i] == '0' and res_b[i] == '0':
res += '1'
carry = 0
elif (res_a[i] == '0' and res_b[i] == '1') or (res_a[i] == '1' and res_b[i] == '0'):
res += '0'
carry = 1
else:
res += '1'
carry = 1
if carry==1:
res += '1'
return res[::-1]