1232.A*B Problem

Description
Calculate ab
Input
Input contains multiple test cases.
Each test case contains two number a and b (0<=a,b<=10^1000),
Output
Output a
b
Sample Input
12345678987654321 98765432123456789
Sample Output
1219326320073159566072245112635269

练习大数模拟可以由乘法竖式得到灵感。具体详解看代码:

#include <iostream>
#include <algorithm>
#include <cstring>
#include <cmath>
#include <string>
#include <cstdio>
#define N 100005
using namespace std;
typedef long long ll;

char s1[N],s2[N];
int a[N],b[N],c[N];
int main()
{
    while(cin>>s1>>s2)
    {
        memset(c,0,sizeof(c));
        int m=strlen(s1);
        int n=strlen(s2);
        int k=m+n;//两数相乘后的位数一定小于等于这两数的位数之和
        for (int i=0; i<m; i++)
            a[i]=s1[m-i-1]-'0';
            //将字符转换成整型数,倒序,a[0],a[1],a[2],分别为个十百位,有利于后面的相乘。
        for (int i=0; i<n; i++)
            b[i]=s2[n-i-1]-'0';
            //根据竖式原理
        for (int i=0; i<m; i++)
            for (int j=0; j<n; j++)
                c[i+j]+=a[i]*b[j];//注意是c[i+j]!
        for (int i=0; i<=k; i++)//大于10就向前进位
        {
            if (c[i]>=10)
            {
                c[i+1]+=c[i]/10;
                c[i]%=10;
            }

        }
        int i=k;
        while(c[i]==0)//去掉前面的0,因为是倒序输出
            i--;
        if (i<0)
            cout<<0;
        else
        {
            for (; i>=0; i--)//倒序输出
                cout<<c[i];
        }
        cout<<endl;
    }
    return 0;
}