forked from gavinfish/leetcode-share
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path067 Add Binary.py
More file actions
36 lines (32 loc) · 823 Bytes
/
067 Add Binary.py
File metadata and controls
36 lines (32 loc) · 823 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
31
32
33
34
35
36
'''
Given two binary strings, return their sum (also a binary string).
For example,
a = "11"
b = "1"
Return "100".
'''
class Solution(object):
def addBinary(self, a, b):
"""
:type a: str
:type b: str
:rtype: str
"""
result = []
carry = val = 0
if len(a) < len(b):
a, b = b, a
lengthA = len(a)
lengthB = len(b)
for i in range(lengthA):
val = carry
val += int(a[-(i + 1)])
if i < lengthB:
val += int(b[-(i + 1)])
carry, val = val // 2, val % 2
result.append(str(val))
if carry:
result.append(str(carry))
return "".join(result[::-1])
if __name__ == "__main__":
assert Solution().addBinary("111", "1") == "1000"