Skip to content

Commit fa15b80

Browse files
committedDec 22, 2020
feat: add-binary
1 parent 70432a5 commit fa15b80

File tree

1 file changed

+43
-0
lines changed

1 file changed

+43
-0
lines changed
 

‎str.add-binary.py

+43
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
class Solution:
2+
"""
3+
67. 二进制求和
4+
https://leetcode-cn.com/problems/add-binary/
5+
给你两个二进制字符串,返回它们的和(用二进制表示)。
6+
输入为 非空 字符串且只包含数字 1 和 0。
7+
"""
8+
def addBinary(self, a: str, b: str) -> str:
9+
if not a:
10+
return b
11+
12+
if not b:
13+
return a
14+
15+
res = ''
16+
ext = 0
17+
i = 0
18+
a_len = len(a)
19+
b_len = len(b)
20+
while i < a_len or i < b_len:
21+
tmp_sum = ext
22+
if i < b_len and i < a_len:
23+
tmp_sum += int(a[a_len - 1 - i]) + int(b[b_len - 1 - i])
24+
elif i < b_len:
25+
tmp_sum += int(b[b_len - 1 - i])
26+
else:
27+
tmp_sum += int(a[a_len - 1 - i])
28+
29+
ext = 1 if tmp_sum >= 2 else 0
30+
if tmp_sum >= 2:
31+
tmp_sum -= 2
32+
res = str(tmp_sum) + res
33+
i += 1
34+
if ext:
35+
res = str(ext) + res
36+
return res
37+
38+
39+
so = Solution()
40+
# 100
41+
print(so.addBinary('11', '1'))
42+
# 10101
43+
print(so.addBinary('1010', '1011'))

0 commit comments

Comments
 (0)
Please sign in to comment.