my first awser


  • 0
    S
        def convert2SameLength(self, a, b):
            a = list(a)
            b = list(b)
            length = max(len(a), len(b))
            for i in range(0, abs(len(a) - len(b))):
                if len(a) > len(b):
                    b.insert(i, 0)
                elif len(a) < len(b):
                    a.insert(i, 0)
            return a, b
        def addBinary(self, a, b):
            a, b = self.convert2SameLength(a, b)
            c = []
            step = 0
            for i in range(len(a) - 1, -1, -1):
                if int(a[i]) + int(b[i]) == 2:
                    # print('step:', step, 'a[i]', a[i], 'b[i]', b[i])
                    c.insert(0, str(step))
                    step = 1
                    # print(c)
                elif int(a[i]) + int(b[i]) == 1:
                    # print('step:', step, 'a[i]', a[i], 'b[i]', b[i])
                    c.insert(0, str(0 if 1 + step == 2 else 1))
                    step = (1 if 1 + step == 2 else 0)
                    # print(c)
                else:
                    # print('step:', step, 'a[i]', a[i], 'b[i]', b[i])
                    c.insert(0, str(step))
                    step = 0
                    # print(c)
            if step == 1:
                c.insert(0, str(step))
            return ''.join(c)
    

Log in to reply
 

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