转成2个二进制数字相加,之后再转回字符串
遍历字符串挨个相加:
class Solution(object):
def addBinary(self, a, b):
"""
:type a: str
:type b: str
:rtype: str
"""
# 思路1 转成二进制数字相加后再转回字符串
return bin(int(a, base=2) + int(b, base=2))[2:]
class Solution(object):
def addBinary(self, a, b):
"""
:type a: str
:type b: str
:rtype: str
"""
# 思路2 逐位相加
# 1补齐2个字符串
max_len = max(len(a), len(b))
subtract = abs(len(a) - len(b))
while subtract > 0:
if len(a) != max_len:
a = '0' + a
elif len(b) != max_len:
b = '0' + b
subtract = subtract - 1
# 进位
plus = 0
r = ''
for i in list(range(max_len - 1, -1, -1)):
# 需要进位
if int(a[i]) + int(b[i]) + plus >= 2:
r = (str(int(a[i]) + int(b[i]) + plus - 2)) + r
plus = 1
# 不需要进位
else:
r = (str(int(a[i]) + int(b[i]) + plus)) + r
plus = 0
if plus == 1:
r = '1' + r
return r