/
add-binary.py
48 lines (41 loc) · 1.05 KB
/
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
37
38
39
40
41
42
43
44
45
46
47
48
# -*- coding: utf-8 -*-
"""
https://leetcode.com/problems/add-binary/
Given two binary strings, return their sum (also a binary string).
For example,
a = "11"
b = "1"
Return "100".
Analysis:
To solution it, must to implement a binaryToInt and intToBInary function, then use add function to calculate.
"""
class Solution(object):
def addBinary(self, a, b):
"""
:type a: str
:type b: str
:rtype: str
"""
# binaryToInt
def b2i(b):
if len(b) == 0:
return 0
sum = 0
for i in range(0, len(b) - 1):
sum = (sum + int(b[i])) * 2
sum += int(b[-1])
return sum
# intToBInary
def i2b(i):
if i == 0:
return '0'
r = []
while i > 0:
if i % 2 == 1:
r.append('1')
else:
r.append('0')
i /= 2
r.reverse()
return ''.join(r)
return i2b(b2i(a) + b2i(b))