题目大意就是高精度A*B,两个高精度相乘,自然的要用到数组。
解题思路:按照小学乘法,数组a分为各个位数与数组b相乘,然后存在第三二维数组数组c[i]中。最后把c中所有加和。因为我菜,尬了三次,第一次忘记把数组倒置,第二次忘记在第三数组计算,头大了。第三次,由于乘法结果,不会考虑到一个为0时,结果为0.反而输出多个0。wa一次。嗯,A+B会了,这题稍微转换一下,就会ac的。
Ac代码如下:
有点臭有点长,见谅
#include <iostream>
#include <cstring>
using namespace std;
void add(char c[], char a, char b[], int n)
{
int len = strlen(b), temp=0, temp2;
int m[3000], sum[3000];
memset(sum, 0, sizeof(sum));
memset(m, 0, sizeof(m));
for (int i=0; i<len; i++)
m[i+n] = b[len-i-1]-'0';
len += n;
for (int i=0; i<len; i++){
temp = (sum[i] + m[i] * (a-'0')) / 10;
sum[i] = (sum[i] + m[i] * (a-'0')) % 10;
sum[i+1] = temp;
}
if (temp){
sum[len] = temp;
len++;
}
for (int i=0; i<len; i++)
c[i] = sum[i] + '0';
}
void Add(char a[], char b[])
{
int temp, sum[3000], n[3000], m[3000];
int max, len1=strlen(a), len2=strlen(b);
max = len1>len2?len1:len2;
memset(n, 0, sizeof(n));
memset(m, 0, sizeof(m));
memset(sum, 0, sizeof(sum));
for (int i=0; i<len1; i++)
m[i] = a[i] - '0';
for (int i=0; i<len2; i++)
n[i] = b[i] - '0';
for (int i=0; i<max; i++){
temp = (sum[i] + n[i] + m[i]) / 10;
sum[i] = (sum[i] + n[i] + m[i]) % 10;
sum[i+1] = temp;
}
if (temp){
sum[max] = temp;
max++;
}
for (int i=0; i<max; i++)
a[i] = sum[i] + '0';
}
int main()
{
int len1, len2;
char a[3000], b[3000], c[1000][1000];
while (scanf("%s%s", a, b)!=EOF){
if (a[0] == '0' || b[0] == '0')
cout << "0" << endl;
else{
len1 = strlen(a);
for (int i=0; i<len1; i++)
add(c[i], a[i], b, len1-1-i);
for (int i=1; i<len1; i++)
Add(c[0], c[i]);
len2 = strlen(c[0]);
for (int i=len2-1; i>=0; i--)
cout << c[0][i];
cout << endl;
for (int i=0; i<len1; i++)
memset(c[i], 0, sizeof(c[i]));
}
}
return 0;
}
嗯...果然代码太臭太长,查了一下网上的代码。get了新方法。一切都在代码中(题解也不给备注,我也不给)
#include <iostream>
#include <cstring>
using namespace std;
void mul(char a[], char b[])
{
if (a[0] == '0' || b[0] == '0')
cout << '0' << endl;
else{
int len1=strlen(a), len2=strlen(b);
int max, m[3000], n[3000], c[3000], temp=0;
memset(c, 0, sizeof(c));
for (int i=0; i<len1; i++)
m[i] = a[len1-i-1]-'0';
for (int i=0; i<len2; i++)
n[i] = b[len2-i-1]-'0';
for (int i=0; i<len1; i++)
for (int j=0; j<len2; j++)
c[i+j] += m[i] * n[j];
max = len1+len2-1;
for (int i=0; i<max; i++){
temp = c[i] / 10;
c[i] = c[i] % 10;
c[i+1] += temp;
}
if (temp)
max++;
for (int i=max-1; i>=0; i--)
cout << c[i];
cout << endl;
}
}
int main()
{
char a[3000], b[3000];
while (scanf("%s%s", a, b)!=EOF)
mul(a, b);
return 0;
}