加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 大数据 > 正文

大数系列——高精度乘法

发布时间:2020-12-14 04:13:45 所属栏目:大数据 来源:网络整理
导读:?Product ? The Problem The problem is to multiply two integers X,Y. ( 0=X,Y10 250 ) 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

?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,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;
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读