自己先写了加法,再不断调用加法,实现大数乘法,然后被大佬的代码惊呆
自己的:
string add(string s1,string s2)
{
int carry=0;
string s3;
reverse(s1.begin(),s1.end());
reverse(s2.begin(),s2.end());
int len1=s1.size(),len2=s2.size();
for(int i=0;i<len1||i<len2;i++)
{
char c1,c2;//为了能够统一写
if(i<len1&&i<len2) {c1=s1[i];c2=s2[i];}
else if(i>=len1) {c1='0';c2=s2[i];}
else {c1=s1[i];c2='0';}
if(c1-'0'+c2-'0'+carry>9)
{
s3+=(c1-'0'+c2+carry-10);
carry=1;
}
else
{
s3+=(c1-'0'+c2+carry);
carry=0;
}
}
if(carry>0) s3+='1';
reverse(s3.begin(),s3.end());
return s3;
}
string single(string s1,char c)
{
if(c=='0') return "0";//防止出现0这种特殊情况!!!
int len1=s1.size(),carry=0;
string s2;
reverse(s1.begin(),s1.end());
for(int i=0;i<len1;i++)
{
int temp=(s1[i]-'0')*(c-'0')+carry;
s2+='0'+temp%10;
carry=temp/10;
}
if(carry>0) s2+='0'+carry;
reverse(s2.begin(),s2.end());
return s2;
}
string multiply(string num1, string num2) {
string num3="0";
int len2=num2.size();
reverse(num2.begin(),num2.end());
for(int j=0;j<len2;j++)
{
string s=single(num1,num2[j]);
if(s!="0")//当非0时需要。。。0的这种特例很难受
{
for(int i=0;i<j;i++)
s+='0';
}
num3=add(s,num3);
}
return num3;
}
};
大佬的:
string multiply(string num1, string num2) {
int i, j;
int m = num1.size(), n = num2.size();
vector<int> product(m + n, 0);
string result;
reverse(num1.begin(), num1.end());
reverse(num2.begin(), num2.end());
// digit i * digit j contributes to digit i + j
for (i = 0; i < m; i++) { //这段直接有效的思路真的棒啊!!
for (j = 0; j < n; j++) {
product[i + j] += (num1[i] - '0') * (num2[j] - '0');
product[i + j + 1] += product[i + j] / 10;
product[i + j] %= 10;
}
}
// remove leading 0; keep last 0 if all 0
for (i = m + n - 1; i > 0 && 0 == product[i]; i--)
;
for (; i >= 0; i--)
result += to_string(product[i]);
return result;
}