1. 程式人生 > >NYOJ 103.大數A+B(大數問題)

NYOJ 103.大數A+B(大數問題)

/*描述
I have a very simple problem for you. Given two integers A and B, your job is to calculate the Sum of A + B.


A,B must be positive.


輸入
The first line of the input contains an integer T(1<=T<=20) which means the number of test cases. Then T lines follow, each line consists of two positive integers, A and B. Notice that the integers are very large, that means you should not process them by using 32-bit integer. You may assume the length of each integer will not exceed 1000.
輸出
For each test case, you should output two lines. The first line is "Case #:", # means the number of the test case. The second line is the an equation "A + B = Sum", Sum means the result of A + B. Note there are some spaces int the equation.
樣例輸入
2
1 2
112233445566778899 998877665544332211
樣例輸出
Case 1:
1 + 2 = 3
Case 2:

112233445566778899 + 998877665544332211 = 1111111111111111110

*/

分析:對於兩個大數相加或相減的問題,一般來說,都是需要借用陣列或字串來進行實現。用陣列或字串來進行儲存大數的每一位數字,然後通過模擬人工加減時的過程來進行運算。

#include<stdio.h>
#include<string.h>
char a[1010],b[1010];//將兩個大數以字串的形式進行輸入
int main()
{
	int t,m=1;
	scanf("%d",&t);
	getchar();
	while(t--)
	{
		int len1,len2,i,j=0,k=0,z=0,len;
		scanf("%s %s",a,b);
		len1=strlen(a);
		len2=strlen(b);
		int x[1010]={0},y[1010]={0},c[1010]={0};
		printf("Case %d:\n",m);
		printf("%s + %s = ",a,b);
		for(i=len1-1;i>=0;i--)//將字串中的數字儲存到陣列中,倒序例如字串為12345,則陣列是54321
		{
			x[j]=a[i]-'0';
			j++;
		}
		for(i=len2-1;i>=0;i--)
		{
			y[k]=b[i]-'0';
			k++;
		}
		if(len1>len2)
			len=len1;
		else
			len=len2;
		for(i=0;i<len;i++)//從兩個陣列的第一位開始進行運算
		{
			c[i]=(x[i]+y[i]+z)%10;//儲存所得的數的個位數
			if(x[i]+y[i]+z>=10)//判斷來那個數相加是否>=10,即是否向下一位進1。
				z=1;
			else
				z=0;
		}
		if(x[i-1]+y[i-1]+z>=10)//判斷最後一位的和是否>=10。
		{
			c[i]=1;
			i++;
		}
		for(i--;i>=0;i--)
			printf("%d",c[i]);
		printf("\n");
		m++;
	}
	return 0;  
}