-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathadd-binary.py
36 lines (31 loc) · 929 Bytes
/
add-binary.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
# https://leetcode.com/problems/add-binary/submissions/
class Solution(object):
def addBinary(self, a, b):
"""
:type a: str
:type b: str
:rtype: str
"""
result = self.binaryToInt(a) + self.binaryToInt(b)
return self.intToBinary(result)
def binaryToInt(self,numberString):
result = 0
for i in range(len(numberString)):
if numberString[i] == "1":
result += 2**(len(numberString)-1-i)
return result
def intToBinary(self,number):
b = []
if number == 0:
return "0"
while number > 0:
d = number % 2
b.append(d)
number = number // 2
b.reverse()
return self.getString(b)
def getString(self,l):
result = ""
for integer in l:
result += str(integer)
return result