8000 Total Runtime: 553 ms · FantasyNew/LintCode_Python@a37f9cf · GitHub
[go: up one dir, main page]

Skip to content

Commit a37f9cf

Browse files
committed
1 parent 4699f2e commit a37f9cf

File tree

1 file changed

+31
-0
lines changed

1 file changed

+31
-0
lines changed

Add_Binary.py

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
class Solution:
2+
# @param {string} a a number
3+
# @param {string} b a number
4+
# @return {string} the result
5+
def addBinary(self, a, b):
6+
if len(a) < len(b): a, b = b, a
7+
pa = len(a) - 1
8+
pb = len(b) - 1
9+
carry = 0
10+
result = ''
11+
12+
while pb >= 0:
13+
sum = int(a[pa]) + int(b[pb]) + carry
14+
result = str(sum%2) + result
15+
carry = sum / 2
16+
pb -= 1
17+
pa -= 1
18+
19+
while pa >= 0:
20+
sum = int(a[pa]) + carry
21+
result = str(sum%2) + result
22+
carry = sum / 2
23+
pa -= 1
24+
< 5C2D /code>25+
if carry == 1: result = '1' + result
26+
return result
27+
28+
if __name__ == '__main__':
29+
a = Solution()
30+
res = a.addBinary('110101','10010001011')
31+
print res

0 commit comments

Comments
 (0)
0