A + B Problem II
Total Submission(s): 165473 Accepted Submission(s): 31614
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
Code:
#include"stdio.h"
#include"string.h"
int main()
{
char num1[1001],num2[1002];
int n1[1002],n2[1002];
int T,ca,i,j,l1,l2,l3;
scanf("%d",&T);
for(ca=1;ca<=T;ca++)
{
memset(n1,0,sizeof(n1));//全部置为0
memset(n2,0,sizeof(n2));
scanf("%s%s",num1,num2);
l1 = strlen(num1);
l2 = strlen(num2);
l3 = l1>l2?l1:l2;
printf("Case %d:\n",ca);//输出
for(i=0;i<l1;i++)
printf("%c",num1[i]);
printf(" + ");
for(i=0;i<l2;i++)
printf("%c",num2[i]);
printf(" = ");
for(i=0,j=l1-1;i<l1,j>=0;j--)//字符串逆置
n1[i++] = num1[j] - '0';
for(i=0,j=l2-1;i<l2,j>=0;j--)
n2[i++] = num2[j] - '0';
for(i=0;i<1001;i++) //相加
{
n1[i] = n1[i] + n2[i];
if(n1[i]>9)
{
n1[i] = n1[i] - 10;
n1[i+1]++;
}
}
if(n1[l3]) l3++;//若最高位有进位,则输出个数加1 <l3为最大长度,有进位说明长度加1>
for(i=l3-1;(i>=0 && n1[i]=='0');i--);
if(i>=0)
for(;i>=0;i--)
printf("%d",n1[i]);
else printf("0");//0+0时空循环中的i变为-1,需另考虑
printf("\n");
if(ca!=T) printf("\n");
}
}
要比较长度啊!! 啊啊啊啊
