这也是经典题。忘了return需要是个string了。
另外忘了a,或者b过界之后,av,bv应该是0. 老了。
最后返回的时候,需要把list里面的数打包成string
‘’.join([str(i) for i in result]). result里面还是数,要重新搞个list,里面是string。
class Solution: def addBinary(self, a: str, b: str) -> str: result = [] # define two cursors for a and b respectively p = len(a)-1 q = len(b)-1 carry = 0 pover = qover = False while not pover or not qover: if not pover: av = int(a[p]) else: av = 0 if not qover: bv = int(b[q]) else: bv = 0 k = av + bv + carry if k <= 1: result.insert(0, k) carry = 0 else: carry = 1 result.insert(0, k-2) p -= 1 if p<0: pover = True q -= 1 if q<0: qover = True if carry == 1: result.insert(0,1) return ''.join([str(i) for i in result])应该是有更简练的写法的。