Tanky WooRSS

百练oj2980 大整数乘法

16 May 2010
这篇博客是从旧博客 WordPress 迁移过来,内容可能存在转换异常。

题目地址:http://poj.grids.cn/problem/2980/ //ID:百练oj2980 大整数乘法 //网站:C++奋斗乐园|C++论坛|算法论坛|ACM/ICPC论坛 //地址:http://www.cppleyuan.com/ //个人主页:www.wutianqi.com //豆瓣小组:http://www.douban.com/group/cppleyuan/

//分析:为方便编程,不急于进位,而将进位问题留待最后统一处理。
//规律:一个数的第i位和另外一个一个数的第j位相乘所得的数,一定是要累加到结果的第 i+j 位上。

#include 
#include 
#include 
#include 
#include 
#include 
using namespace std;

#define MAX_NUM 210
unsigned an1[MAX_NUM];
unsigned an2[MAX_NUM];
unsigned result[MAX_NUM*2]; //现开始忘了*2

char szLine1[MAX_NUM];
char szLine2[MAX_NUM];

int main()
{
    gets(szLine1);  
    gets(szLine2);
    int i, j;
    memset(an1, 0, sizeof(an1));
    memset(an2, 0, sizeof(an2));
    memset(result, 0, sizeof(result));

    //下面将szLine1中存储的字符串形式的整数倒序转换到an1中去。
    int nLen1 = strlen(szLine1);    
    j = 0;
    for(i = nLen1-1; i >= 0; i--)
        an1[j++] = szLine1[i] - '0';

    int nLen2 = strlen(szLine2);
    j = 0;
    for(i = nLen2-1; i >= 0; i--)
        an2[j++] = szLine2[i] - '0';

    for(i = 0; i < nLen2; i++)
        for(j = 0; j < nLen1; j++)
        {
            result[i+j] += an1[i] * an2[j];        //逐位相乘
        }

    for(i = 0; i < MAX_NUM * 2; i++)
        if(result[i] >= 10)        //看是否大于10,大于则进位
        {
            result[i+1] += result[i] / 10;
            result[i] %= 10;
        }

    //输出结果,考虑 0 的特殊情况。
    bool startOutput = false;
    for(i = MAX_NUM * 2-1; i >= 0; i--)   //一定要减一.
        if(startOutput)
            printf("%d", result[i]);
        else if(result[i])
        {
            printf("%d", result[i]);
            startOutput = true;
        }
    if(!startOutput)
        printf("0");
    return 0;
}