43. 字串相乘(大數相乘模擬)
阿新 • 來源:網路 • 發佈:2021-02-19
技術標籤:leetcode刷題
就是模擬乘法的一個過程,這裡我們不按正常的乘法做法來做:我們在每一位相乘後不進行進位,而是保留相乘得到的結果,到最後相加的時候再去進行進位。
如下圖所示:

程式碼如下所示:
class Solution {
public:
string multiply(string num1, string num2) {
vector<int> A,B;
int n = num1.size(),m = num2.size();
for(int i = n-1; i >= 0; --i) A.push_back(num1[i]-'0');
for(int i = m-1; i >= 0; --i) B.push_back(num2[i]-'0');
vector<int> C(n+m,0);
for(int i = 0; i < n;++i){
for(int j = 0; j < m;++j){
C[i+j] += A[i]*B[j];
}
}
string res;
int t = 0;
for(int i = 0; i < C.size(); ++i){
t += C[i];
res.push_back((t%10)+'0');
t = t/10;
}
while(res.size()>1 && res[res.size()-1] == '0') res.pop_back();
reverse(res.begin(),res.end());
return res;
}
};
