For example,
a = "11"
b = "1"
Return "100".
这题的做法和前面一题plus one 一样,区别在于需要将两个string先相加,再判断是否要进位。
直接上代码吧。
class Solution: # @param a, a string # @param b, a string # @return a string def addBinary(self, a, b): a=list(a) b=list(b) for i in range(len(a)): a[i]=int(a[i]) for i in range(len(b)): b[i]=int(b[i]) lena=len(a) lenb=len(b) if lena<lenb: a,b=b,a itera=len(a)-1 iterb=len(b)-1 while itera>=0 and iterb>=0: a[itera]+=b[iterb] itera-=1 iterb-=1 for i in reversed(range(len(a))): digit=a[i]%2 carry=a[i]/2 a[i]=digit if i>0: a[i-1]+=carry if carry==1: a.insert(0,1) for i in range(len(a)): a[i]=str(a[i]) return "".join(a)
时间: 2024-10-10 10:14:06