题意:给定两个大数,求相乘结果
题解:利用数组来存中间结果以及结果。
void mulInteger_2(string &str1, string &str2) //两个整数相乘
{
int num1[200] = {0};
int num2[200] = {0};
int result[300] = {0};
//auto_ptr<string> output(new string (str2));
for(int i = 0; i < str1.size(); i++)
{
num1[i] = (int)(str1[str1.size() - 1 - i] - '0');
}
for(int i = 0; i < str2.size(); i++)
{
num2[i] = (int)(str2[str2.size() - 1 - i] - '0');
}
for(int i = 0; i < str1.size(); i++)
{
for(int j = 0; j < str2.size(); j++)
{
result[i+j] += num1[i] * num2[j];
}
}
for(int i = 0; i < 300; i++)
{
if(result[i] >= 10)
{
result[i+1] += result[i]/10;
result[i] = result[i]%10;
}
}
int i, j, count = 0;
for( i = 300-1; i >= 0; i--)
if(result[i]) break;
//string output;
char *output = new char[i+2];
for(j = i; j >= 0; j--)
{
output[count] = (char)(result[j] + '0');
count++;
//cout << result[j];
}
output[count] = '\0';
//cout << str2[count] << endl
str2.assign(output);
<span style="white-space:pre"> </span>cout<<output;
}