-
Notifications
You must be signed in to change notification settings - Fork 20
/
AddBinary.py
executable file
·80 lines (72 loc) · 2 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
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
# -*- coding: UTF-8 -*-
# Given two binary strings, return their sum (also a binary string).
#
# For example,
# a = "11"
# b = "1"
# Return "100".
#
# Python, Python 3 all accepted.
# Maybe the ugliest code I have ever written since I learned Python.
class AddBinary(object):
def addBinary(self, a, b):
"""
:type a: str
:type b: str
:rtype: str
"""
if a is None or b is None:
return ""
if len(a) == 0:
return b
if len(b) == 0:
return a
# if it needs to plus one
flag = False
if len(a) >= len(b):
longer = a
shorter = b
else:
longer = b
shorter = a
result = ""
i = len(longer) - 1
j = len(shorter) - 1
while i >= 0:
if j < 0:
if longer[i] == '1':
if flag:
result += '0'
else:
result += '1'
else:
if flag:
result += '1'
flag = False
else:
result += '0'
else:
if longer[i] == '1' and shorter[j] == '1':
if flag:
result += '1'
else:
result += '0'
flag = True
elif longer[i] == '0' and shorter[j] == '0':
if flag:
result += '1'
else:
result += '0'
flag = False
# (l == '1' && s == '0') || (l == '0' && s == '1')
else:
if flag:
result += '0'
flag = True
else:
result += '1'
i -= 1
j -= 1
if flag:
result += '1'
return result[::-1]