给出两个用字符串表示的二进制数,返回他们的和(也用字符串表示)
例如:
a ="11"
b ="1"
返回"100".
b ="1"
返回"100".
class Solution: def addBinary(self , a , b ): # write code here res = "" add_flag = False max_length = max(len(a), len(b)) if max_length == len(a): b = b.rjust(max_length, '0') else: a = a.rjust(max_length, '0') for ca, cb in zip(reversed(a), reversed(b)): if not ca&nbs***bsp;not cb: break add_res=int(ca)+int(cb) #有进位时此位置加一 if add_flag: add_res+=1 add_flag=False #和大于等于2时,更新和字符串 if add_res>=2: res= str(add_res%2)+res add_flag=True #更新和字符串 else: res=str(add_res)+res if add_flag==True: res='1'+res return res