12 Lines Python Emulation


  • 0

    The basic idea is that num1[i] and num2[j] should together make contribution to the answer[i + j].

    class Solution(object):
        def multiply(self, num1, num2):
            num1, num2, l1, l2, carry, start = num1[::-1], num2[::-1], len(num1), len(num2), 0, 0
            ans = [ 0 for i in xrange(l1 + l2) ]
            for i in xrange(len(num1)):
                for j in xrange(len(num2)):
                    ans[i + j] += int(num1[i]) * int(num2[j])
            for i in xrange(len(ans)):
                ans[i], carry = (ans[i] + carry ) % 10, (ans[i] + carry) / 10
            ans = map(str, ans)
            answer = ''.join(ans)[::-1]
            while start < len(answer) and answer[start] == '0':
                start += 1
            return answer[start:] if start != len(answer) else '0'
    

Log in to reply
 

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