7 Lines Straightforward Python


  • 0
    class Solution(object):
        def addBinary(self, a, b):
            a, b, carry, idx, ans = a[::-1], b[::-1], 0, 0, ''
            while idx < len(a) or idx < len(b):
                ans += str((int(b[idx]) + carry) % 2) if idx >= len(a) else (str((int(a[idx]) + carry) % 2) if idx >= len(b) else str((int(a[idx]) + int(b[idx]) + carry) % 2) )
                carry = (int(b[idx]) + carry) / 2 if idx >= len(a) else ( (int(a[idx]) + carry) / 2 if idx >= len(b) else (int(a[idx]) + int(b[idx]) + carry) / 2 )
                idx += 1
            ans += '1' if carry else ''
            return 0 if len(ans) == 0 else ans[::-1]
    

Log in to reply
 

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