洛谷刷题8:A*B Problem(P1303)
当两个数的位数大大超过int后,我们用的依然是数组去存储这两个数的每一位,然后依据竖式计算,进行每一位的运算
#include<iostream>
#include<algorithm>
#include<iomanip>
#include<math.h>
#include<cstring>
#include<cstdio>
using namespace std;
int a[10001], b[10001], c[30000];
char s[10001], t[10001];
int main()
{
cin >> s >> t;
int x = strlen(s), y = strlen(t);
for (int i = 1; i <= x; i++)a[i] = s[x - i] - '0';
for (int i = 1; i <= y; i++)b[i] = t[y - i] - '0';
for (int i = 1; i <= x; i++)
for (int j = 1; j <= y; j++)
c[i + j - 1] += a[i] * b[j];
int len = x + y;
for (int i = 1; i < len; i++)
if (c[i] > 9)
{
c[i + 1] += c[i] / 10;
c[i] %= 10;
}
while (c[len] == 0 && len > 1)len--;
for (int i = len; i >= 1; i--)cout << c[i];
return 0;
}
注意这一句
c[i + j - 1] += a[i] * b[j];
结果的第i+j-1位,是a的第i位与b的第j位相乘得出的