5/21/2020

[LeetCode] 43. Multiply Strings

Simulate the process of multiplying 2 numbers.

Time Complexity = O( len(nums1) * len(nums2) )

class Solution:
    def multiply(self, num1: str, num2: str) -> str:
    
        def mul(a, b):
            result = []
            carry = 0
            
            for n in a[::-1]:
                t = n * b + carry
                result.append(t%10)
                carry = t // 10
            
            if carry:
                result.append(carry)
            
            return result[::-1]
            
        def plus(a, b):
            
            i, j = len(a)-1, len(b)-1
            carry = 0
            result = []
            
            while i >= 0 or j >= 0 or carry:
                t = carry
                if i >= 0:
                    t += a[i]
                if j >= 0:
                    t += b[j]
                result.append(t%10)
                carry = t // 10
                
                i -= 1
                j -= 1
            
            return result[::-1]
            
        
        num1 = [int(n) for n in num1]
        num2 = [int(n) for n in num2]
        
        base = 0
        tmp = []
        
        for n in num2[::-1]:
            t = mul(num1, n)
            for i in range(base):
                t.append(0)
            
            tmp.append(t)
            base += 1
        
        result = [0]
        
        for i in range(len(tmp)):
            result = plus(tmp[i], result)
        
        return ''.join(map(str,result)) if result[0] != 0 else '0'

Edited on 11/07/2021. Tidy the solution.

No comments:

Post a Comment