大数相乘

题目:请使用代码计算1234567891011121314151617181920*2019181716151413121110987654321。

答:

#include "stdafx.h"
#include <iostream>
#include <string>

using namespace std;

int _tmain(int argc, _TCHAR* argv[])
{
    string strOne;
    string strTwo;
    cout<<"输入第一个乘数:";
    cin>>strOne;
    cout<<"输入第二个乘数:";
    cin>>strTwo;
    int lengthOne = strOne.size();
    int lengthTwo = strTwo.size();
    int lengthResult = lengthOne * lengthTwo;
    int *result = new int[lengthResult];
    memset(result, 0, lengthResult * sizeof(int));

    int count = 1;
    int i, j, k;
    for (i = lengthTwo - 1; i >= 0; i--)
    {
        k = lengthResult - count;
        for (j = lengthOne - 1; j >= 0; j--)
        {
            result[k--] += (strTwo[i] - '0') * (strOne[j] - '0');
        }
        count++;
    }

    for (i = lengthResult - 1; i > 0; i--)
    {
        while(result[i] >= 10)
        {
            result[i] -= 10;
            result[i - 1]++;
        }
    }
    for (i = 0; i < lengthResult; i++)
    {
        if (0 != result[i])
        {
            break;
        }
    }

    cout<<strOne<<" * "<<strTwo<<" = "<<endl;
    for (; i < lengthResult; i++)
    {
        cout<<result[i];
    }

    delete [] result;
    cout<<endl;
    return 0;
}

运行界面如下:

原文地址:https://www.cnblogs.com/venow/p/2670158.html