-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathadd_binary.py
More file actions
36 lines (35 loc) · 949 Bytes
/
Copy pathadd_binary.py
File metadata and controls
36 lines (35 loc) · 949 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
'''''''''''''''''''''''''''''''''''''''''''''''''''
> System: Ubuntu
> Author: ty-l8
> Mail: [email protected]
> File Name: add_binary.py
> Created Time: 2017-08-20 Sun 00:05
'''''''''''''''''''''''''''''''''''''''''''''''''''
class Solution(object):
def addBinary(self, a, b):
"""
:type a: str
:type b: str
:rtype: str
"""
return self.convert_back(self.convert(a) + self.convert(b))
def convert(self, binary):
"""
:type binary: str
:rtype: int
"""
result = 0
for c in binary:
result = result*2+(1 if c=='1' else 0)
return result
def convert_back(self, value):
"""
:type value: int
:rtype: str
"""
if value == 0: return '0'
bits = []
while value:
bits.append(str(value % 2))
value //= 2
return ''.join(bits[::-1])