码迷,mamicode.com
首页 > 编程语言 > 详细

[leetcode]Add Binary @ Python

时间:2014-06-08 20:28:04      阅读:300      评论:0      收藏:0      [点我收藏+]

标签:c   style   class   blog   code   java   

原题地址: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".

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

代码一:

bubuko.com,布布扣
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
bubuko.com,布布扣

代码二:

bubuko.com,布布扣
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
bubuko.com,布布扣

 

[leetcode]Add Binary @ Python,布布扣,bubuko.com

[leetcode]Add Binary @ Python

标签:c   style   class   blog   code   java   

原文地址:http://www.cnblogs.com/zuoyuan/p/3776018.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!