题目描述:
题解:
1.定义一个add函数,有a b c三个输入参数,分别对应两个加数和一个进位,innum,resnum两个返回参数,分别对应向前一位的进位和这一位的结果。如果a+b+c>=2,innum = 1,resnum = a+b+c-innum
2.判断输入a b两个参数长度是否相等,如果不想等,则将a b中较短的前面补0。
3.从a b最后一位开始调用add函数,结果保存在result数组中,然后将result数组按照逆序输出为字符串。
class Solution: def addBinary(self, a: str, b: str) -> str: def add(a, b, c): if a + b + c >= 2: innum = 1 resnum = a + b + c - 2 else: resnum = a + b + c innum = 0 return resnum, innum newstr = "" if len(a) > len(b): for i in range(len(a) - len(b)): newstr = newstr + "0" b = newstr + b if len(b) > len(a): for i in range(len(b) - len(a)): newstr = newstr + "0" a = newstr + a result = [] length = len(a) c = 0 for i in range(length - 1, -1, -1): resnum, innum = add(int(a[i]), int(b[i]), c) result.append(resnum) c = innum if c > 0: result.append(c) resstr = "" for i in range(len(result) - 1, -1, -1): resstr = resstr + str(result[i]) return resstr