forked from shichao-an/leetcode-python
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsolution.py
More file actions
27 lines (27 loc) · 759 Bytes
/
solution.py
File metadata and controls
27 lines (27 loc) · 759 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
class Solution:
# @param a, a string
# @param b, a string
# @return a string
def addBinary(self, a, b):
res = []
# a is longer than b
if len(a) < len(b):
b, a = a, b
n = len(a)
m = len(b)
c = 0 # Carry bit
r = 0 # Result bit
# i = n - 1 ... 0
for k in range(n):
i = n - 1 - k
if k < m:
j = m - 1 - k
r = (int(a[i]) + int(b[j]) + c) % 2
c = (int(a[i]) + int(b[j]) + c) / 2
else:
r = (int(a[i]) + c) % 2
c = (int(a[i]) + c) / 2
res.insert(0, str(r))
if c == 1:
res.insert(0, str(c))
return ''.join(res)