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
#include
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=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;  
}


你可能感兴趣的:(大数运算)