LeetCode 0043. Multiply Strings Solution in Java, Python, C++, JavaScript, Go & Rust | Explanation + Code

CoderIndeed
0
0043. Multiply Strings

Description

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

Solution 1: Simulating Mathematical Multiplication

Assume the lengths of num1 and num2 are m and n respectively, then the length of their product can be at most m + n.

The proof is as follows:

  • If num1 and num2 both take the minimum value, then their product is {10}^{m - 1} × {10}^{n - 1} = {10}^{m + n - 2}, with a length of m + n - 1.
  • If num1 and num2 both take the maximum value, then their product is ({10}^m - 1) × ({10}^n - 1) = {10}^{m + n} - {10}^m - {10}^n + 1, with a length of m + n.

Therefore, we can apply for an array of length m + n to store each digit of the product.

From the least significant digit to the most significant digit, we calculate each digit of the product in turn, and finally convert the array into a string.

Note to check whether the most significant digit is 0, if it is, remove it.

The time complexity is O(m × n), and the space complexity is O(m + n). Here, m and n are the lengths of num1 and num2 respectively.

PythonJavaC++GoTypeScriptRustC#PHPKotlinJavaScript
class Solution: def multiply(self, num1: str, num2: str) -> str: if num1 == "0" or num2 == "0": return "0" m, n = len(num1), len(num2) arr = [0] * (m + n) for i in range(m - 1, -1, -1): a = int(num1[i]) for j in range(n - 1, -1, -1): b = int(num2[j]) arr[i + j + 1] += a * b for i in range(m + n - 1, 0, -1): arr[i - 1] += arr[i] // 10 arr[i] %= 10 i = 0 if arr[0] else 1 return "".join(str(x) for x in arr[i:])(code-box)

Post a Comment

0Comments

Post a Comment (0)

#buttons=(Accept !) #days=(20)

Our website uses cookies to enhance your experience. Check Now
Accept !