Uva 10106 Product (高精度相乘)

 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

题目解析:

输入两个整数X, Y. (0<=X,Y<10250),求两个整数的积。


#include<stdio.h>
#include<string.h>
#include<stdlib.h>
const int MAX = 1000;

void getDigits(int num[],char str[])//把字符串保存在int类型的数组中
{
	char digit;
	int len = strlen(str);	
	for(int i=0;i<len;++i) {
		digit=str[i];
		num[len-i-1]=digit-'0';//字符串倒叙保存	
	}
}
void multiply(int a[],int b[],int sum[])
{
	/*
	数组a和数组b逐位相乘,并把结果保存于数组sum
	12345*12345 5与12345中的每位相乘
	对于数组sum sum[i+j]在i=0,j=1,2,3,4,5时保存的是5和各位相乘的结果	
	而在i=1,j=1,2,3,4,5时保存的是4和各位相乘的结果,并累加上次相乘的结果
	*/
	for(int i=0;i<MAX;i++) {
		for(int j=0;j<MAX;j++) {
			sum[i+j] += a[i]*b[j];
		}
	}
	/*将十位以上的数字向上进位
	 *将剩余的数字保存在自己位置上
	 * /
	for(int i=0;i<MAX*2-1;i++)
	{
		sum[1+i] += sum[i]/10;
		sum[i] = sum[i]%10;
	}
}
int main()
{
	char num1[MAX],num2[MAX];
	int a[MAX];
	int b[MAX];
	int sum[MAX*2];
	while(scanf("%s%s",&num1,&num2)!=EOF)
	{
		if(strcmp(num1,"0")==0||strcmp(num2,"0")==0) {
			printf("0\n");
			continue;
		}
		getchar();
		memset(a,0,sizeof(a)); //初始化数组a,b
		memset(b,0,sizeof(b));
		memset(sum,0,sizeof(sum));
		getDigits(a,num1);
		getDigits(b,num2);
		multiply(a,b,sum);
		int j=MAX*2-1;
		while(sum[j]==0) {
			j--;
		}
		for(int i = j;i >= 0;i--) {
			printf("%d",sum[i]);
		}
		printf("\n");
	}
	return 0;
}

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值