思路:按位求和,同时设置一个符号位,初始为0,分六种情况相加
原题如下:
通过代码如下:
class Solution(object):
def addBinary(self, a, b):
"""
:type a: str
:type b: str
:rtype: str
"""
la = len(a)
lb = len(b)
ll = abs(la - lb)
result = ""
m = '0'
for i in range(ll):
if la > lb:
b = '0' + b
if lb > la:
a = '0' + a
for i in range(len(a)):
if a[-i-1] == b[-i-1] == '0' and m == '0':
result = '0' + result
elif a[-i-1] != b[-i-1] and m == '0':
result = '1' + result
elif a[-i-1] == b[-i-1] == '1' and m == '0':
result = '0' + result
m = '1'
elif a[-i-1] == b[-i-1] == '0' and m == '1':
result = '1' + result
m = '0'
elif a[-i-1] != b[-i-1] and m == '1':
result = '0' + result
m = '1'
elif a[-i-1] == b[-i-1] == '1' and m == '1':
result = '1' + result
m = '1'
if m == '1':
result = '1' + result
return result