forked from Jack-Lee-Hiter/AlgorithmsByPython
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path67. AddBinary.py
More file actions
28 lines (28 loc) · 746 Bytes
/
67. AddBinary.py
File metadata and controls
28 lines (28 loc) · 746 Bytes
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
'''
Given two binary strings, return their sum (also a binary string).
For example,
a = "11"
b = "1"
Return "100".
'''
class Solution(object):
def addBinary(self, a, b):
lenA, lenB = len(a), len(b)
a, b = list(a), list(b)
if lenA == 0:
return b
if lenB == 0:
return a
carry, r = 0, ['']*(max(lenA, lenB)+1)
for i in range(len(r)):
p1, p2 = 0, 0
if i < lenA:
p1 = int(a[lenA-1-i])
if i < lenB:
p2 = int(b[lenB-1-i])
sum = p1 + p2 + carry
r[len(r)-1-i] = str(sum%2)
carry = sum // 2
return str(int("".join(r)))
s = Solution()
print(s.addBinary('10110', '101'))