Given two binary strings, return their sum (also a binary string).
For example,
a = "11"
b = "1"
Return "100"
.
Subscribe to see which companies asked this question
按位相加,还是有些边界条件需要处理的
class Solution(object):
def addBinary(self, a, b):
la = len(a)
lb = len(b)
if la < lb:
a,b = b,a
la,lb = lb,la
res = [''] * (max(len(a),len(b)) + 1)
prp = 0
for i in xrange(1,lb+1):
ta = int(a[-i])
tb = int(b[-i])
#print ta,tb,prp,
resi = ta + tb + prp
if resi > 1:
resi -= 2
prp = 1
else:
prp = 0
res[-i] = str(resi)
#print res
for i in xrange(lb+1,la+1):
ta = int(a[-i])
resi = ta + prp
if resi > 1:
resi -= 2
prp = 1
else:
prp = 0
res[-i] = str(resi)
#print res
if prp == 1:
res[0] = str(prp)
res = ''.join(res)
return res