-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathQ67.py
More file actions
30 lines (27 loc) · 870 Bytes
/
Q67.py
File metadata and controls
30 lines (27 loc) · 870 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
29
30
class Solution:
def addBinary(self, a: str, b: str) -> str:
a = [int(val) for val in a[::-1]]
b = [int(val) for val in (b[::-1])]
result = []
carryBit = 0
i,j = 0,0
while i<len(a) and j<len(b):
result.insert(0,str((a[i]+b[j]+carryBit)%2))
carryBit = (a[i]+b[j]+carryBit)//2
i+=1
j+=1
while i<len(a):
result.insert(0,str((a[i]+carryBit)%2))
carryBit = (a[i]+carryBit)//2
i+=1
while j<len(b):
result.insert(0,str((b[j]+carryBit)%2))
carryBit = (b[j]+carryBit)//2
j+=1
if carryBit:
result.insert(0,str(carryBit))
return "".join(result)
if __name__ == '__main__':
a = "1"
b = "111"
print(Solution().addBinary(a,b))