A + B Problem II
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)Total Submission(s): 407964 Accepted Submission(s): 79058
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
基本思想:竖式运算,用字符串输入,然后每位数减去'0'再相加。
搜了很多代码都是计算输出的时候没有去掉前面的0,比如:000+1=001 。
看着别人的代码,顺着思路改了一下现在的输出是没有前面的0的,即:000+1=1 。
这两种写法都能AC,不去掉0的输出时比较简单。
还有就是注意输出的时候除最后一组数之外,每两组数之间有一个空行
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<iostream>
const int maxn=1e6+10;
int a[maxn],b[maxn],c[maxn];
char num1[maxn],num2[maxn];
int main()
{
int t;
int k=1;
int i;
scanf("%d",&t);
while(t--)
{
int sum;
int flag=0;
memset(a,0,sizeof(a));
memset(b,0,sizeof(b));
memset(c,0,sizeof(c));
scanf("%s %s",num1,num2);
int l1=strlen(num1);
int l2=strlen(num2);
for(i=0;i<l1;i++) a[i]=num1[l1-1-i]-'0';
for(i=0;i<l2;i++) b[i]=num2[l2-1-i]-'0';//字符串转换成数字
int ml=std::max(l1,l2);//找到最长的字符串长度
for(sum=0,i=0;i<ml;i++)
{
c[i]=(a[i]+b[i]+sum)%10;
sum=(a[i]+b[i]+sum)/10;
}
if(sum) c[ml]=1;
printf("Case %d:\n",k++);
printf("%s + %s = ",num1,num2);
if(c[ml]==1) printf("1");
for(i=ml-1;i>=0;i--)
{
if(c[i]!=0)
{
flag++;
printf("%d",c[i]);
}
else if(c[i]==0&&flag!=0)
{
printf("0");
flag++;
}
else if(c[i]==0&&flag==0) continue;
}
if(c[0]==0&&flag==0) printf("0");
/*这种写法是不去掉开头的0的
for(i=ml-1;i>=0;i--) printf("%d",c[i]);*/
printf("\n");
if(t) printf("\n");
}
return 0;
}