[leetcode]Add Binary @ Python

原题地址:https://oj.leetcode.com/problems/add-binary/

题意:

Given two binary strings, return their sum (also a binary string).

For example,
a = "11"
b = "1"
Return "100".

解题思路:提供两种实现方式吧。

代码一:

class Solution:
# @param a, a string
# @param b, a string
# @return a string
def addBinary(self, a, b):
aIndex = len(a)-1; bIndex = len(b)-1
flag = 0
s = ''
while aIndex>=0 and bIndex>=0:
num = int(a[aIndex])+int(b[bIndex])+flag
flag = num/2; num %= 2
s = str(num) + s
aIndex -= 1; bIndex -= 1
while aIndex>=0:
num = int(a[aIndex])+flag
flag = num/2; num %= 2
s = str(num) + s
aIndex -= 1
while bIndex>=0:
num = int(b[bIndex])+flag
flag = num/2; num %= 2
s = str(num) + s
bIndex -= 1
if flag == 1:
s = '' + s
return s

代码二:

class Solution:
# @param a, a string
# @param b, a string
# @return a string
def addBinary(self, a, b):
length = max(len(a),len(b)) + 1
sum = ['' for i in range(length)]
if len(a) <= len(b):
a = '' * ( len(b) - len(a) ) + a
if len(a) > len(b):
b = '' * ( len(a) - len(b) ) + b
flag = 0
i = len(a) - 1
while i >= 0:
if int(a[i]) + int(b[i]) + flag == 3:
sum[i+1] = ''
flag = 1
elif int(a[i]) + int(b[i]) + flag == 2:
sum[i+1] = ''
flag = 1
elif int(a[i]) + int(b[i]) + flag == 1:
sum[i+1] = ''
flag = 0
else:
sum[i+1] = ''
flag = 0
i = i - 1
if flag == 1:
sum[0] = ''
if flag == 0:
sum = sum[1:length]
sum = ''.join(sum)
return sum
上一篇:linux下svn客户端安装及环境配置(转)


下一篇:spring cloud配置中心属性加密处理