/*
43. Multiply Strings My Submissions QuestionEditorial Solution
Total Accepted: 59659 Total Submissions: 255286 Difficulty: Medium
Given two numbers represented as strings, return multiplication of the numbers as a string.
Note:
The numbers can be arbitrarily large and are non-negative.
Converting the input string to integer is NOT allowed.
You should NOT use internal library such as BigInteger.
Subscribe to see which companies asked this question
*/
/*
解题思路:
具体步骤在代码中已经写的比较清楚了。本题的思想就是一个数的第i位数与另一个数的第j位相乘,其相乘的结果一定放在结果数中的i+j-1处。最后做进位处理就可以了。
*/
class Solution {
public:
string multiply(string num1, string num2) {
//大数相乘(之前写过,就直接搬代码了)
string res="";
//两个数的位数
int m = num1.size(), n = num2.size();
//一个i位数乘以一个j位数,结果至少是i+j-1位数
vector<long long> tmp(m + n - 1);
//每一位进行笛卡尔乘法
for (int i = 0; i < m; i++){
int a = num1[i] - '0';
for (int j = 0; j < n; j++){
int b = num2[j] - '0';
tmp[i + j] += a*b;
}
}
//进行进位处理,注意左侧是大右侧是小
int carry = 0;
for (int i = tmp.size() - 1; i >= 0; i--){
int t = tmp[i] + carry;
tmp[i] = t % 10;
carry = t /10;
}
//若遍历完仍然有进位
while (carry != 0){
int t = carry % 10;
carry /= 10;
tmp.insert(tmp.begin(), t);
}
//将结果存入到返回值中
for (auto a : tmp){
res = res + to_string(a);
}
if(res.size()>0&&res[0]=='0')return "0";
return res;
}
};