题目:
给你两个二进制字符串 a
和 b
,以二进制字符串的形式返回它们的和。
示例 1:
输入:a = "11", b = "1"
输出:"100"
示例 2:
输入:a = "1010", b = "1011"
输出:"10101"
class Solution(object):
def addBinary(self, a, b):
i = len(a)
j = len(b)
temp = 0
res = ''
while i>0 and j>0:
if int(a[i-1])+int(b[j-1])+temp>=2:
res = str((int(a[i-1])+int(b[j-1])+temp)%2)+res
temp = 1
i-=1
j-=1
else:
res = str(int(a[i-1])+int(b[j-1])+temp)+res
temp = 0
i-=1
j-=1
while i>0:
if int(a[i-1])+temp>=2:
res = str((int(a[i-1])+temp)%2)+res
temp = 1
i-=1
else:
res = str(int(a[i-1])+temp)+res
temp = 0
i-=1
while j>0:
if int(b[j-1])+temp>=2:
res = str((int(b[j-1])+temp)%2)+res
temp = 1
j-=1
else:
res = str(int(b[j-1])+temp)+res
temp = 0
j-=1
if temp==1:
return str(temp)+res
else:
return res
temp用来保存进位的,写的有点复杂...不写了,去看看别人是怎么解决的