Friday, September 12, 2014

Leetcode: Add Binary @Python

class Solution:
    # @param a, a string
    # @param b, a string
    # @return a string
    def addBinary(self, a, b):
        n=len(a)
        m=len(b)
        if n>=m:
            c=a[:n-m]
        else:
            c=b[:m-n]
        flag=0
        rst=''
        i=-1
        while -i<=min(n,m):
            if a[i]=='1' and b[i]=='1':
                if flag==0:
                    rst='0'+rst
                else:
                    rst='1'+rst
                flag=1
            elif a[i]=='0' and b[i]=='0':
                if flag==0:
                    rst='0'+rst
                else:
                    rst='1'+rst
                flag=0
            elif flag==0:
                rst='1'+rst
                flag=0
            else:
                rst='0'+rst
                flag=1
            i-=1
        for i in reversed(range(abs(n-m))):
            if c[i]=='1' and flag==1:
                rst='0'+rst
                flag=1
            elif c[i]=='0' and flag==1:
                rst='1'+rst
                flag=0
            else:
                rst=c[i]+rst
                flag=0
        if flag==1:
            rst='1'+rst
        return rst

1 comment :

  1. Hello. I just started trying out the leetcode problems. For this problem, I find that people always employ a relatively long answer. Is there a reason the following answer is not chosen? Thank you!

    intAB = int(a, 2) + int(b,2)
    return "{0:b}".format(intAB)

    ReplyDelete