Skip to content

Commit a59cf38

Browse files
authored
Create 0067-add-binary.py
1 parent 502ce28 commit a59cf38

File tree

1 file changed

+19
-0
lines changed

1 file changed

+19
-0
lines changed

python/0067-add-binary.py

+19
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
class Solution:
2+
def addBinary(self, a: str, b: str) -> str:
3+
res = ""
4+
carry = 0
5+
6+
a, b = a[::-1], b[::-1]
7+
for i in range(max(len(a), len(b))):
8+
bitA = ord(a[i]) - ord('0') if i < len(a) else 0
9+
bitB = ord(b[i]) - ord('0') if i < len(b) else 0
10+
11+
total = bitA + bitB + carry
12+
char = str(total % 2)
13+
res = char + res
14+
carry = total // 2
15+
16+
if carry:
17+
res = "1" + res
18+
19+
return res

0 commit comments

Comments
 (0)