Very simple and easy to understand Python code, only 1 for loop


  • 0
    def addBinary(self, a, b):
        a = list(a); b = list(b)
        r = ['' for i in range(max(len(a), len(b))+1)]
        carry = 0
        for i in range(len(r)):
            p1 = 0; p2 = 0;
            if i < len(a): p1 = int(a[len(a)-1-i])
            if i < len(b): p2 = int(b[len(b)-1-i])
            sum = p1 + p2 + carry
            r[len(r)-1-i] = str(sum%2); carry = sum/2
        return str(int(''.join(r)))

Log in to reply
 

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