Problem
Given two non-negative integers num1
and num2
represented as strings, return the product of num1
and num2
, also represented as a string.
Example 1:
1 |
|
Example 2:
1 |
|
Note:
The length of both num1
and num2
is < 110.
Both num1
and num2
contain only digits 0-9
.
Both num1
and num2
do not contain any leading zero, except the number 0 itself.
You must not use any built-in BigInteger library or convert the inputs to integer directly.
Explanation
-
When two numbers are multiple, the result’s length will be maximum of len(num1)+len(num2).
-
When we multiple two numbers, we start from the lowest digit. When we multiple two lowest digits, its result will be maximum of two digits, and this result’s lowest digit’s index will be indexOf(digit1)+indexOf(digit2)+1, the highest digit’s index will be indexOf(digit1)+indexOf(digit2).
-
For example, if two input numbers are 23 and 45. We have the following operations:
1
2
3
4
5
6
72 3 <- num1 4 5 <- num2 0 0 0 0 <- result 0 0 1 5 <- 5*3 0 1 1 5 <- 5*2 0 2 3 5 <- 4*3 1 0 3 5 <- 4*2
-
After we get the result array, we create a string builder. Then loop through the result array, if the iterated element is 0 and string builder’s length is also 0, that means the current element is a leading zero, so we ignore it. At the end, if the string builder’s length is 0, then we return 0; else we return the string builder’s string format.
Solution
1 |
|