python solution


  • 0
    G

    class Solution(object):

    def addBinary(self, a, b):
        
        res = ""
        a= [int(x) for x in a]
        b = [int(x) for x in b]
    
        n = self.zerofill(a, b)
        print(a)
        print(b)
        c = 0
        s = [0 for i in range(n)]
    
        for i in range(n-1,-1,-1):
            s[i] = a[i]+b[i]+c
            c = s[i] // 2
            s[i] = s[i] %2
    
    
        res =  s if s[0] == 1 else s[1:]
        return self.list2str(res)
    
    def list2str(self,x):
        s = ""
        for i in range(len(x)):
            s += str(x[i])
    
        return s
    
    def zerofill(self,a, b):
        na,nb = len(a),len(b)
        if na > nb:
            for i in range(na-nb):
                b.insert(0,0)
        elif na < nb:
            for i in range(nb-na):
                a.insert(0,0)
        a.insert(0, 0)
        b.insert(0, 0)
        return max(na,nb)+1

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.