大数系列——高精度乘法

 Product 

The Problem

The problem is to multiply two integers X, Y. (0<=X,Y<10250)

The Input

The input will consist of a set of pairs of lines. Each line in pair contains one multiplyer.

The Output

For each input pair of lines the output line should consist one integer the product.

Sample Input

12
12
2
222222222222222222222222

Sample Output

144
444444444444444444444444

本来是水的一题的速度写出来后没想到拖了这么久老AC不了,怎么修改都A不了。。。

本来的思路是这样的:倒序输入数组里面,然后再二重循环相乘,个位数累加给result的第i+j个数,其他位累加给i+j+1,虽然没有和网上大部分做法一样用到leap来作为进位数,但结果据我测试多次效果是一样的。

但不知道怎么回事,老是WA。。。

注意到乘数为0时的情况,于是我判断输入的string第一个字符是否为0,是就输出0并进行下一轮,还是WA

后来我考虑到如果遇到012*01这种情况,就没有进行计算了,于是我吧判断放在后面,判断result是不是空的。。。还是WA了。。

太失望了,我已经没办法了,难道非得用通用的那种方法吗。。。

先贴出WA代码吧。。。

#include<iostream>
#include<string>
using namespace std;

int main()
{
	string str1, str2;
	while (cin >> str1 >> str2)
	{
		int a[250] = {0}, b[250] = {0}, res[300] = {0};
		for (int i = 0; i < (int)str1.size(); i++)
			a[i] = str1[(int)str1.size() - i - 1] - '0';
		for (int i = 0; i < (int)str2.size(); i++)
			b[i] = str2[(int)str2.size() - i - 1] - '0';
		for (int i = 0; i < (int)str1.size(); i++)
			for (int j = 0; j < (int)str2.size(); j++)	
			{
				int temp = a[i] * b[j] + res[i +j];
				res[i + j] = temp % 10;
				res[i + j + 1] += temp / 10;
			}
		int i;
		for (i = 299; i >= 1; i--)
			if (res[i])
				break;
		for (;i >= 0; i--)
			cout << res[i];
		cout << endl;
	}
	return 0;
}

不知道到底是为什么。。。



改用进位方法了。。。

然后就AC了。。。

#include <stdio.h>
#include <string.h>
int main()
{  
	int u, i, j, k, n, m, temp, leap;
    char str2[10000], str1[10000], res[10000];
    while(gets(str1) != NULL)
    {
		gets(str2);
        memset(res, 0, sizeof(res));  
        n = strlen(str1);  
        m = strlen(str2);
		for(i = 0; i < n; i++)
            str1[i] -= '0';
        for(i = 0; i < m; i++)
            str2[i] -= '0';
        for(k = n - 1; k >= 0; k--)
        {
            leap = 0;
            u = n - 1 - k;
            for(j = m - 1; j >= 0; j--)
            {
                temp = str2[j] * str1[k] + leap + res[u];  
                res[u] = temp % 10;  
				u++;
                leap = temp / 10;  
            }
            if(leap)
			{
                res[u] = leap;
				u++;
			}
        }
        for(i = u - 1; i > 0; i--) 
            if(res[i])
                break;
        for(; i >= 0; i--)
            printf("%d", res[i]);
        printf("\n");
    }
    return 0;
}



转载于:https://www.cnblogs.com/java20130723/archive/2013/03/24/3212187.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值