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:
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.
Example:
Example 1:
Input: num1 = "2", num2 = "3"
Output: "6"
Example 2:
Input: num1 = "123", num2 = "456"
Output: "56088"
answer:
class Solution {
public:
string multiply(string num1, string num2) {
string res = "";
int m = num1.size(), n = num2.size();
vector<int> vals(m + n); // m 位数和 n 位数相乘结果会有 m+n 位,ps. 2*20 = 040
for (int i = m - 1; i >= 0; --i) { // 列式乘法
for (int j = n - 1; j >= 0; --j) {
int mul = (num1[i] - '0') * (num2[j] - '0');
int p1 = i + j, p2 = i + j + 1, sum = mul + vals[p2];
vals[p1] += sum / 10;
// 这里一定要 += !!,因为这个列式乘法和我们的列式乘法还不太一样,
//它不是一下子第一行乘以第二行某个数,而是第一行的某个 数乘以第二行的某个数
// 这就是说会有折回去的时候,所以高位也要加上原来的数
vals[p2] = sum % 10;
}
}
for (int val : vals) {
if (!res.empty() || val != 0) res.push_back(val + '0');
// 类似于上边的 ps. 情况,要将打头的没用的 0 去掉,刚开始是 res等于空,而且 value = 0,所以一直不会进入这个 if,直到 value != 0 之后才开始导入到 result 中。
}
return res.empty() ? "0" : res;
}
};
relative point get√:
vals(m + n); 创建一个vector,大小为 m + n, 初始化为 0.
hint :
类似于小学的列式乘法题
8 9 <- num2
7 6 <- num1
-------
5 4
4 8
6 3
5 6
-------
6 7 6 4