-
Notifications
You must be signed in to change notification settings - Fork 25
Expand file tree
/
Copy path67_AddBinary.py
More file actions
63 lines (50 loc) · 1.24 KB
/
Copy path67_AddBinary.py
File metadata and controls
63 lines (50 loc) · 1.24 KB
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
50
51
52
53
54
55
56
57
58
59
60
61
62
63
# coding: utf8
"""
题目链接: https://leetcode.com/problems/add-binary/description.
题目描述:
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
"""
if not a:
return b
if not b:
return a
result = []
la = len(a)
lb = len(b)
ll = min(la, lb)
lr = max(la, lb)
ra = a[::-1]
rb = b[::-1]
carry = 0
for i in range(ll):
vs = int(ra[i]) + int(rb[i]) + carry
if vs >= 2:
carry = 1
else:
carry = 0
result.append(str(vs % 2))
for i in range(ll, lr):
if lr == la:
vs = int(ra[i]) + carry
else:
vs = int(rb[i]) + carry
if vs >= 2:
carry = 1
else:
carry = 0
result.append(str(vs % 2))
if carry:
result.append(str(carry))
result.reverse()
return ''.join(result)