Multiply Strings
https://leetcode.com/problems/multiply-strings/description/
Thoughts
/*
* @lc app=leetcode id=43 lang=cpp
*
* [43] Multiply Strings
*/
// @lc code=start
class Solution {
public:
string multiply(string num1, string num2) {
const int M = num1.length(), N = num2.length();
vector<int> pos(M + N);
for (int i = M - 1; i >= 0; --i) {
for (int j = N - 1; j >= 0; --j) {
int r = (num1[i] - '0') * (num2[j] - '0');
const int p0 = i + j, p1 = p0 + 1;
r += pos[p1];
pos[p1] = r % 10;
pos[p0] += r / 10;
}
}
string res;
for (const auto i : pos) {
if (res.empty() && i == 0) continue;
res.push_back(i + '0');
}
return res.empty() ? "0" : res;
}
};
// @lc code=endLast updated