Given two binary strings, return their sum (also a binary string).

For example,
a = "11"
b = "1"
Return "100".

思路

注意考虑几个条件即可:a和b的长度不同,则位数短的字符串首先停止迭代;注意循环过程中和循环结束后的进位。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
class Solution(object):
def addBinary(self, a, b):
"""
:type a: str
:type b: str
:rtype: str
"""
lena = len(a)
lenb = len(b)
count = summ = carry = 0
result = ''
while (count < lena or count < lenb):
if (count < lena and count < lenb):
summ = int(a[-count-1]) + int(b[-count-1]) + carry
else:
if (lena > lenb):
summ = int(a[-count-1]) + carry
else:
summ = int(b[-count-1]) + carry
if (summ == 2):
carry = 1
summ = 0
elif (summ == 3):
carry = 1
summ = 1
else:
carry = 0
result = str(summ) + result
count += 1
if (carry == 1):
result = str(carry) + result
return result