A + B Problem II

A + B Problem II

Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 99134 Accepted Submission(s): 18806


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
 
View Code
 1 #include<stdio.h>  
2 #include<string.h>
3 #define N 1005
4 char A[N],B[N],sum[N];
5 int main()
6 {
7 int T,i,j,k,x,sign;
8 while(scanf("%d",&T)!=EOF)
9 {
10 for(i=0;i<T;i++)
11 {
12 if(i)
13 printf("\n");
14 scanf("%s%s",&A,&B);
15 j=strlen(A)-1,k=strlen(B)-1;
16 for(x=0,sign=0;(j+1)&&(k+1);j--,k--,x++)
17 {
18 if((A[j]-'0')+(B[k]-'0')+sign<10)
19 {
20 sum[x]=(A[j]-'0')+(B[k]-'0')+sign;
21 sign=0;
22 }
23 else
24 {
25 sum[x]=(A[j]-'0')+(B[k]-'0')+sign-10;
26 sign=1;
27 }
28 }
29 if(j+1)
30 {
31 for(;j>=0;j--,x++)
32 {
33 if(A[j]-'0'+sign<10)
34 {
35 sum[x]=(A[j]-'0')+sign;
36 sign=0;
37 }
38 else
39 {
40 sum[x]=0;
41 sign=1;
42 }
43 }
44 }
45 else if(k+1)
46 {
47 for(;k>=0;k--,x++)
48 {
49 if(B[k]-'0'+sign<10)
50 {
51 sum[x]=(B[k]-'0')+sign;
52 sign=0;
53 }
54 else
55 {
56 sum[x]=0;
57 sign=1;
58 }
59 }
60 }
61 if(sign)
62 sum[x]=1;
63 else
64 x--;
65 printf("Case %d:\n",i+1);
66 printf("%s + %s = ",A,B);
67 while(x>-1)
68 printf("%d",sum[x--]);
69
70 printf( "\n" );
71 }
72 }
73 return 0;
74 }
原文地址:https://www.cnblogs.com/zsj576637357/p/2360178.html