-
-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathaddBinary.py
49 lines (39 loc) · 1.19 KB
/
addBinary.py
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
36
37
38
39
40
41
42
43
44
45
46
47
48
49
"""
time: 6 min
erros: none!
"""
class Solution:
def addBinary(self, a: str, b: str) -> str:
rtn = []
a1 = len(a) - 1
b1 = len(b) - 1
carry = 0
while a1 >= 0 or b1 >= 0:
d1 = 0
d2 = 0
if a1 >= 0: d1 = ord(a[a1]) - ord('0')
if b1 >= 0: d2 = ord(b[b1]) - ord('0')
total = d1 + d2 + carry
carry = total // 2
digit = total % 2
rtn.append(chr(digit + ord('0')))
a1 -= 1
b1 -= 1
if carry:
rtn.append(chr(carry + ord('0')))
return "".join(rtn[::-1])
def addBinary(self, a: str, b: str) -> str:
rtn = deque()
a = list(a)
b = list(b)
carry = 0
while a or b:
a1 = ord(a.pop()) - ord('0') if a else 0
b1 = ord(b.pop()) - ord('0') if b else 0
total = a1 + b1 + carry
digit = total % 2
carry = total // 2
rtn.appendleft(str(digit))
if carry:
rtn.appendleft(str(carry))
return "".join(rtn)