43. Multiply Strings
Problem statement:
Given two non-negative integers num1
and num2
represented as strings, return the product of num1
and num2
.
Note:
- The length of both
num1
andnum2
is < 110. - Both
num1
andnum2
contains only digits0-9
. - Both
num1
andnum2
does not contain any leading zero. - You must not use any built-in BigInteger library or convert the inputs to integer directly.
Solution:
This problem is a math related question. The following figures give a very brief explanation about how to match the digits multiplication to the final result.
We should loop from the back of two strings, this pattern follows the multiplication rules. Suppose the two digits form num1 is i and num2 is j, the final position in multiplication is i + j and i + j + 1. We need to update the mul[i + j + 1] by addition and mul[i + j + 1] by carry.
We should think carefully about the corner case.
- leading zero.
- For the test case, such as "999", "0", if we ignore the leading zero, the return string is "". When return value, do this test.
Time complexity is O(m * n).
class Solution { public: string multiply(string num1, string num2) { string mul_str; vector<int> mul(num1.size() + num2.size(), 0); for(int i = num1.size() - 1; i >= 0; i--){ for(int j = num2.size() - 1; j >= 0; j--){ int dig_mul = (num1[i] - '0') * (num2[j] - '0') + mul[i + j + 1]; mul[i + j + 1] = dig_mul % 10; mul[i + j] += dig_mul / 10; } } for(auto digit : mul){ if(!(digit == 0 && mul_str.empty())) { mul_str.push_back(digit + '0'); } } return mul_str.empty() ? "0" : mul_str; } };