要求:字符串相乘,类似415字符串相加
思路:
法一:num2每一位乘num1后加至ans
class Solution {
public:
string addStrings(string num1, string num2) {
if(num1.length()<num2.length())swap(num1,num2);
string ans="";
int l1=num1.length()-1,l2=num2.length()-1;
int carry=0;
for(;l1>=0&&l2>=0;--l1,--l2){
int num=num1[l1]-'0'+num2[l2]-'0'+carry;
if(num>=10){
carry=num/10;
num=num%10;
}
else carry=0;
ans.push_back(num+'0');
}
for(;l1>=0;--l1){
int num=num1[l1]-'0'+carry;
if(num>=10){
carry=num/10;
num=num%10;
}
else carry=0;
ans.push_back(num+'0');
}
if(carry!=0)ans.push_back(carry+'0');
reverse(ans.begin(),ans.end());
return ans;
}
string multiply(string num1, string num2) {
//123,456对个位是123加6次
//优化:6乘123每一位再加
if(num1=="0"||num2=="0")return "0";
string ans="0";
int len1=num1.length(),len2=num2.length();
string izero="";
for(int i=len1-1;i>=0;--i){
string jzero="";
cout<<ans<<endl;
for(int j=len2-1;j>=0;--j){
ans=addStrings(ans,to_string((num1[i]-'0')*(num2[j]-'0'))+izero+jzero);
jzero+="0";
}
izero+="0";
}
return ans;
}
};
法二:先把每一位相乘存到数组里,最后再进位转字符串,比上面节省了很多次加法时间
class Solution {
public:
string multiply(string num1, string num2) {
if (num1 == "0" || num2 == "0") {
return "0";
}
int m = num1.size(), n = num2.size();
auto ansArr = vector<int>(m + n);
for (int i = m - 1; i >= 0; i--) {
int x = num1.at(i) - '0';
for (int j = n - 1; j >= 0; j--) {
int y = num2.at(j) - '0';
ansArr[i + j + 1] += x * y;
}
}
for (int i = m + n - 1; i > 0; i--) {
ansArr[i - 1] += ansArr[i] / 10;
ansArr[i] %= 10;
}
int index = ansArr[0] == 0 ? 1 : 0;
string ans;
while (index < m + n) {
ans.push_back(ansArr[index]);
index++;
}
for (auto &c: ans) {
c += '0';
}
return ans;
}
};