leetcode刷题二十一
题目叙述
给你两个二进制字符串,返回它们的和(用二进制表示)。
输入为 非空 字符串且只包含数字 1 和 0。
题目解答
class Solution:
def addBinary(self, a: str, b: str) -> str:
l1 = len(a)
l2 = len(b)
l = 0
c = []
out = ''
r = '0'
if l1 == l2:
l = l1
pass
elif l1 > l2:
l = l1
for i in range(l1 - l2):
b = b[::-1]
b = b + '0'
b = b[::-1]
else:
l = l2
for j in range(l2 - l1):
a = a[::-1]
a = a + '0'
a = a[::-1]
for k in range(l):
if int(a[l - k - 1]) ^ int(b[l - k - 1]) ^ int(r) == 1:
out += '1'
else:
out += '0'
if int(r) * (int(a[l - k - 1]) ^ int(b[l - k - 1])) + int(a[l - k - 1]) * int(b[l - k - 1]) == 1:
r = '1'
else:
r = '0'
if r == '0':
return out[::-1]
else:
out = out + r
return out[::-1]