LintCode Q408 Add Binary string in Python

  • Jinhai ZHOU
  • 4 Minutes
  • 2016年11月14日
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
from collections import deque
class Solution:
# @param {string} a a number
# @param {string} b a number
# @return {string} the result
def addBinary(self, a, b):
# Write your code here
# string manipulation
if len(a) < len(b):
a, b = b, a
# len(a) > len(b)
carry = 0
result = deque()
pa = len(a) - 1
pb = len(b) - 1
while pb >= 0:
this_sum = int(a[pa], 2) + int(b[pb], 2) + carry
carry = this_sum / 2
this_sum = this_sum % 2
result.appendleft(this_sum)
pa -= 1
pb -= 1
while pa >= 0:
this_sum = int(a[pa], 2) + carry
carry = this_sum / 2
this_sum = this_sum % 2
result.appendleft(this_sum)
pa -= 1
if carry:
result.appendleft(carry)
result = map(str, result)
return ''.join(result)
知识共享许可协议
本作品采用知识共享署名-相同方式共享 4.0 国际许可协议进行许可。