-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathAddBinary.py
More file actions
74 lines (52 loc) · 1.24 KB
/
Copy pathAddBinary.py
File metadata and controls
74 lines (52 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
64
65
66
67
68
69
70
71
72
73
74
'''
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
"""
length_a = len(a)
length_b = len(b)
if length_a == 0:
return b
if length_b == 0:
return a
# print(a[-1])
# print(a[0:-1])
if a[-1] =='1' and b[-1] == '1':
return self.addBinary(self.addBinary(a[0:-1],b[0:-1]),'1')+'0'
elif a[-1] =='0' and b[-1] == '0':
return self.addBinary(a[0:-1],b[0:-1])+'0'
else:
return self.addBinary(a[0:-1],b[0:-1])+'1'
# for x in range(len(a)-1,-1,-1):
# print(a[x])
#
# while length_a > -1 and length_b > -1:
# result += a[length_a]
a = "11"
b = "1"
sol = Solution()
print(sol.addBinary(a,b))
'''
Things learnt
Say a = "1234"
How do you print 4 ?
a[-1]
How do you print 123 ?
a[0:-1]
Try to match with string not int
wrong way
if a[-1] ==1 and b[-1] == 1:
correct
if a[-1] =='1' and b[-1] == '1':
return self.addBinary(a[0:-1],b[0:-1])+1
TypeError: must be str, not int
'''