【A + B Problem II 】【HDU - 1002 】(高精度加法)

题目:

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

Input

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. 

Output

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. Output a blank line between two test cases. 

Sample Input

2
1 2
112233445566778899 998877665544332211

Sample Output

Case 1:
1 + 2 = 3

Case 2:
112233445566778899 + 998877665544332211 = 1111111111111111110

解题报告:

题目意思非常简单,就是求解两个数的加和,但是由于二者非常大,会爆unsigned,所以要使用大数加法来模拟实现。

模拟起来没有什么特别的难处,有一点需要去考虑就是两个都是0的情况,或者是多个0的缀和数字。

赠送几组样例

0 0 

000 00000

1000 0001

99 10

9 1

9 8

基本上注意这些,就可以正常ac 了,难在0 的这个地方,容易忽略。

#include
#include
#include
#include
#include
using namespace std;
typedef long long ll;


int T;

int main()
{
	scanf("%d",&T);
	for(int kase=1;kase<=T;kase++)
	{
		char a[1010];
		char b[1010];
		int numa[1010]={0};
		int numb[1010]={0};
		int numc[1010]={0};
		scanf("%s",a);
		scanf("%s",b);
		
		int len1=strlen(a);
		int len2=strlen(b);
		int cnt1=0,cnt2=0;
		for(int i=len1-1;i>=0;i--)
		{
			numa[cnt1++]=a[i]-'0';
		}
		for(int i=len2-1;i>=0;i--)
		{
			numb[cnt2++]=b[i]-'0';
		}
		int length=max(cnt1,cnt2);
		int c=0;
		for(int i=0;i=10)
		{
			numc[length]=c/10;
			numc[length-1]=c%10;
			//length++;
		}
//		printf("before: %d\n",length);
		while(numc[length]==0)
			length--; 
//		printf("after: %d\n",length);
//		printf("length: %d\n",length+1);
		printf("Case %d:\n",kase);
		printf("%s",a);
		printf(" + ");
		printf("%s",b);
		printf(" = ");
		if(length<0)
		{
			printf("0\n");
		}
		else
		{
			for(int i=length;i>=0;i--)
			{
				printf("%d",numc[i]);
			}
			printf("\n");
		}
		if(kase!=T)
				printf("\n");
	}	
}

 

你可能感兴趣的:(模拟)