Skip to content

43. Multiply Strings

Math String Simulation

Problem - Multiply Strings

Medium

Given two non-negative integers num1 and num2 represented as strings, return the product of num1 and num2, also represented as a string.

Note: You must not use any built-in BigInteger library or convert the inputs to integer directly.

 

Example 1:

Input: num1 = "2", num2 = "3"
Output: "6"

Example 2:

Input: num1 = "123", num2 = "456"
Output: "56088"

 

Constraints:

  • 1 <= num1.length, num2.length <= 200
  • num1 and num2 consist of digits only.
  • Both num1 and num2 do not contain any leading zero, except the number 0 itself.

Solutions

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
class Solution:
    def multiply(self, num1: str, num2: str) -> str:
        if num1 == "0" or num2 == "0":
            return "0"

        m, n = len(num1), len(num2)
        array = [0] * (m + n)

        for i in range(m - 1, -1, -1):
            val1 = int(num1[i])
            for j in range(n - 1, -1, -1):
                val2 = int(num2[j])
                array[i + j + 1] += val1 * val2

        for i in range(m + n - 1, 0, -1):
            array[i - 1] += array[i] // 10
            array[i] %= 10

        i = 0 if array[0] else 1
        return "".join(str(val) for val in array[i:])

Submission Stats:

  • Runtime: 31 ms (54.06%)
  • Memory: 17.8 MB (69.83%)