考虑设置进位标识符
0725更新
class Solution:
def addBinary(self, a: str, b: str) -> str:
if a == '':
return b
elif b == '':
return a
cura = len(a) - 1
curb = len(b) - 1
jinwei = 0
res = ''
while cura >= 0 or curb >= 0 or jinwei != 0:
if cura < 0:
aval = 0
else:
aval = int(a[cura])
if curb < 0:
bval = 0
else:
bval = int(b[curb])
tempres = aval + bval + jinwei
if tempres == 3:
jinwei = 1
tempres = 1
elif tempres == 2:
jinwei = 1
tempres = 0
else:
jinwei = 0
res = str(tempres) + res
if cura >= 0:
cura -= 1
if curb >= 0:
curb -= 1
return res
class Solution:
def addBinary(self, a: str, b: str) -> str:
while len(a) < len(b):
a = '0' + a
while len(a) > len(b):
b = '0' + b
sumstr = str(int(a) + int(b))
sumstr = [letter for letter in sumstr]
length = len(sumstr)
jinwei = False
for i in range(length):
cur = length - i - 1
if sumstr[cur] == '2':
if jinwei == True:
sumstr[cur] = '1'
elif jinwei == False:
sumstr[cur] = '0'
jinwei = True
elif sumstr[cur] == '1':
if jinwei == True:
sumstr[cur] = '0'
elif jinwei == False:
sumstr[cur] = '1'
jinwei = False
elif sumstr[cur] == '0':
if jinwei == False:
sumstr[cur] = '0'
elif jinwei == True:
sumstr[cur] = '1'
jinwei = False
res = ''
for letter in sumstr:
res += letter
if jinwei == True:
res = '1' + res
return res