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>
#define M 1001
int T;
char string[2][M];//存放字符串
int lenth;
int number[2][M];//存放数字
int sum[M];//存放加和
int cases;//大循环次数
int main(void)
{
cases=0;
scanf("%d",&T);
while(T--){
cases++;
scanf("%s%s",&string[0],&string[1]);//读取字符串
memset(sum,0,sizeof(sum));//数组初始化
memset(number,0,sizeof(number));//数组初始化
for(int i=0;i<2;i++){
lenth=strlen(string[i])-1;//lenth为当前字符串的长度
for(int j=0;lenth>-1;j++,lenth--){
number[i][j]=string[i][lenth]-'0';//把字符翻译为数字,存入相应的数组中,注意字符串存入和取出顺序相反,其实就是一个stack
}
}
lenth=strlen(string[0])>strlen(string[1])?strlen(string[0]):strlen(string[1]);//lenth为较长字符串的长度
for(int i=0;i<lenth;i++){
sum[i]+=number[0][i]+number[1][i];//是+=,不是=,因为还有可能从较低位进位上来的数字
if(sum[i]>=10){//如果这一位的数字之和大于0,就要除10向前进位,这一位的数字对10取余
sum[i+1]+=sum[i]/10;
sum[i]=sum[i]%10;
}
}
lenth=(sum[lenth]==0)?lenth:lenth+1;//如果lenth这一位不是0,说明从低位进位过来了数字
printf("Case %d:\n",cases);//输出循环次数
printf("%s + %s = ",string[0],string[1]);//注意输出格式,不要忘记空格
for(int i=lenth-1;i>0;i--)//从高位输出,不是从低位输出
printf("%d",sum[i]);
printf("%d\n",sum[0]);
if(T)
printf("\n");//最后一次循环不要输出空格
}
return 0;
}