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
題解----數組模擬儲存大數的每一位,再相乘,進位。注意 0*123和123*0的特殊情況
#include<iostream>
#include<cstdio>
#include<cstring>
using namespace std;
int a[300],b[300],c[700];
char str_1[300], str_2[300];
int main()
{
	int i,p,q,j;
	while(cin>>str_1)
	{
		q=0;
		cin>>str_2;
		if(strcmp(str_1,"0")==0||strcmp(str_2,"0")==0)
		{
			printf("0\n");
			continue;
		}
		memset(a,0,sizeof(a));
		memset(b,0,sizeof(b));
		memset(c,0,sizeof(c));
		for(i=strlen(str_1)-1,p=299;i>=0;i--,p--)
			a[p]=str_1[i]-'0';
		for(i=strlen(str_2)-1,p=299;i>=0;i--,p--)
			b[p]=str_2[i]-'0';
		for(i=299;i>=0;i--)
		{
			for(j=299,p=699-(299-i);j>=0;j--,p--)//關鍵是P的變化,每乘一位P要加1
			{
				c[p]=c[p]+a[i]*b[j];
			}
		}
		for(i=699;i>=0;i--)
		{
			c[i-1]=c[i-1]+c[i]/10;
			c[i]=c[i]%10;
		}
		for(i=0;i<700;i++)
		{
			if(c[i]==0&&q==0)
				continue;
			else
			{
				cout<<c[i];
				q=1;
			}
		}
		puts("");
	}
	return 0;
}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章