1. 程式人生 > 實用技巧 >HDU 1002 A + B Problem II(大數相加)

HDU 1002 A + B Problem II(大數相加)

HDU 1002

A + B Problem II

Problem Description

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

#include<stdio.h>
#include<string.h>
int main(){
	int i,j,k,n,flag=0,len1,len2,sum,len=0;
	while(scanf("%d",&n)!=EOF){
		for(k=1;k<=n;k++){
			char s1[1001],s2[1001];
			int ans[1001]={0};
			scanf("%s %s",s1,s2);
			len1=strlen(s1);
        	len2=strlen(s2);
        	if(len1>=len2)
        	{	len=len1;
				j=len2-1;
            	for(i=len1-1;i>=0;i--){
            		if(j>=0){
            		sum=(int)s1[i]+(int)s2[j--]-96+flag;
            		if(sum>=10){
            			ans[i]=sum%10;
            			flag=1;
					}
					else{
						ans[i]=sum;
						flag=0;
					}
				}
				else{
					sum=(int)s1[i]-48+flag;
					if(sum>=10){
            			ans[i]=sum%10;
            			flag=1;
					}
					else{
						ans[i]=sum;
						flag=0;
					}
				}
        	}
        }
        	else if(len1<len2)
        	{	len=len2;
				j=len1-1;
            	for(i=len2-1;i>=0;i--){
            		if(j>=0){
            		sum=(int)s1[j--]+(int)s2[i]-96+flag;
            		if(sum>=10){
            			ans[i]=sum%10;
            			flag=1;
					}
					else{
						ans[i]=sum;
						flag=0;
					}
				}
				else{
					sum=(int)s2[i]-48+flag;
					if(sum>=10){
            			ans[i]=sum%10;
            			flag=1;
					}
					else{
						ans[i]=sum;
						flag=0;
					}
				}
        	}
		}
		if(k>1)	printf("\n");
		printf("Case %d:\n",k);
		if(flag==0){
		printf("%s + %s = ",s1,s2);
		for(i=0;i<len-1;i++)	printf("%d",ans[i]);
		printf("%d\n",ans[len-1]);
	}
		if(flag==1){
		printf("%s + %s = 1",s1,s2);
		for(i=0;i<len-1;i++)	printf("%d",ans[i]);
		printf("%d\n",ans[len-1]);
	}
	}
}
} 

Note:

演算法和思路是很簡單的,主要是實現的方法,我這個基礎知識太爛,搞了半天
就是從後往前運算,然後進位就行唄
我最得意的一點是 flag的用法
最前一位的時候flag是1的話就在前面+1,是0就不用加