[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 = '1' + 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 = ['0' for i in range(length)]
        if len(a) <= len(b):
            a = '0' * ( len(b) - len(a) ) + a
        if len(a) > len(b):
            b = '0' * ( 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] = '1'
                flag = 1
            elif int(a[i]) + int(b[i]) + flag == 2:
                sum[i+1] = '0'
                flag = 1
            elif int(a[i]) + int(b[i]) + flag == 1:
                sum[i+1] = '1'
                flag = 0
            else:
                sum[i+1] = '0'
                flag = 0
            i = i - 1
        if flag == 1:
            sum[0] = '1'
        if flag == 0:
            sum = sum[1:length]
        sum = ''.join(sum)
        return sum

 

posted @ 2014-06-08 11:45  南郭子綦  阅读(3939)  评论(2编辑  收藏  举报