Saturday, May 24, 2014

LeetCode (Python): Add Binary

Given two binary strings, return their sum (also a binary string).
For example,
a = "11"
b = "1"
Return "100".

Solution:

class Solution:
    # @param a, a string
    # @param b, a string
    # @return a string
    def addBinary(self, a, b):
        solution = []
        sum = 0
        for i in range(0,max(len(a),len(b))):
            if i < len(a) and a[len(a)-1-i]=='1':
                sum += 1
            if i < len(b) and b[len(b)-1-i]=='1':
                sum += 1
            solution.insert(0,str(sum%2))
            sum /= 2
        if sum >0:
            solution.insert(0,str(sum%2))
        return ''.join(solution)

1 comment :

  1. nice answer, except isn't 'insert' a bit heavy on time complexity? would this be sped up by pre-allocating 'solution' and setting items to solution[-i-1]?

    ReplyDelete