43. Multiply Strings
LeetCode 43. 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 = "123", num2 = "456"
Output: "56088"Constraints:
1 <= num1.length, num2.length <= 200num1andnum2consist of digits only.Both
num1andnum2do not contain any leading zero, except the number0itself.
Tags
Math, String
Solution
If m, n are lengths of two strings respectively, the length of the product of both is either m+n-1 or m+n. Based on this conclusion, we build an int array whose length is m+n to store the interim result. In particular, we add the product of num1[i] and num2[j] to ints[i+j+1], because the carry of the result will be added to ints[i+j]. After multiplication, we process the carries on each bit. Finally, we trim the leading zero and return the result string converted from the array.
Complexity
Time complexity:
Space complexity:
Code
Reference
Last updated
Was this helpful?