43. Multiply Strings字符串相乘

时间:2022-06-16 00:52:31

网址:https://leetcode.com/problems/multiply-strings/submissions/

参考:https://leetcode.com/problems/multiply-strings/discuss/17605/Easiest-JAVA-Solution-with-Graph-Explanation

把乘法分解为最最基础的加法,从后往前循环。

class Solution {
public:
string multiply(string num1, string num2) {
int siz1 = num1.size(), siz2 = num2.size();
if(num1 == "" || num2 == "")
return "";
vector<int> sums(siz1+siz2, );
int mul = ;
int p1, p2;
int sum;
string ans = "";
for(int i = siz1-; i>=; i--)
{
for(int j = siz2-; j>=; j--)
{
mul = (int)(num1[i]-'') * (int)(num2[j]-'');
p1 = i+j;
p2 = i+j+;
sum = sums[p2] + mul;
sums[p1] += sum / ;
sums[p2] = sum % ;
}
}
for(auto i : sums)
{
ans.append(to_string(i));
}
if(ans[] == '')
ans = ans.substr(, ans.size()-);
return ans;
}
};

43. Multiply Strings字符串相乘