Given two binary strings, return their sum (also a binary string).
For example,
a = "11"
b = "1"
Return "100"
.
Solution: string manipulation, pay attention to "carry"
Running Time: O(n)
class Solution:
# @param a, a string
# @param b, a string
# @return a string
def addBinary(self, a, b):
lenA = len(a)
lenB = len(b)
if lenA < lenB:
tempA = '0'*(lenB-lenA) + a
tempB = b
else:
tempA = a
tempB = '0'*(lenA-lenB) + b
len_AB = max(lenA, lenB)
result = [0] * len_AB
flag = 0
for i in range(len_AB-1, -1, -1):
sumI = int(tempA[i]) + int(tempB[i]) + flag
if sumI == 3:
result[i] = 1
flag = 1
elif sumI == 2:
result[i] = 0
flag = 1
elif sumI == 1:
result[i] = 1
flag = 0
if flag == 1:
result.insert(0, 1)
return ''.join(str(i) for i in result)