A + B Problem II
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 277311 Accepted Submission(s): 53511
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 max(int a,int b)
{
return a>b?a:b;
}
int main()
{
int t;
int cont=0;
scanf("%d",&t);
while(t--)
{
char a[1000];
char b[1000];
int c[1000];
int aa[1000];
int bb[1000];
scanf("%s%s",a,b);
int i;
int j=0;
memset(bb,0,sizeof(bb));
memset(aa,0,sizeof(aa));
memset(c,0,sizeof(c));
for(i=strlen(a)-1;i>=0;i--)
{
aa[j]=a[i]-'0';
j++;
}
j=0;
for(i=strlen(b)-1;i>=0;i--)
{
bb[j]=b[i]-'0';
j++;
}
j=0;
int n=max(strlen(a),strlen(b));
for(i=0;a[i]!='\0';i++)
{
c[i]+=aa[i];
}
for(i=0;b[i]!='\0';i++)
{
c[i]+=bb[i];
}
for(i=0;i<n;i++)
{
if(c[i]>=10)
{
c[i+1]+=c[i]/10;
c[i]=c[i]%10;
}
}
printf("Case %d:\n",++cont);
if(c[n]==0)
{
printf("%s + %s = ",a,b);
for(i=n-1;i>=0;i--)
printf("%d",c[i]);
printf("\n");
if(t!=0)
printf("\n");
}
else
{
printf("%s + %s = ",a,b);
for(i=n;i>=0;i--)
printf("%d",c[i]);
printf("\n");
if(t!=0)
printf("\n");
}
}
}
/*必先倒置.倒置相加 从最后一位开始进位 而不是从最高位开始进位.*/
#include<stdio.h>
#include<string.h>
#include<iostream>
using namespace std;
int main()
{
int t;
int kase=0;
scanf("%d",&t);
while(t--)
{
char a[2000];
char b[2000];
int aa[2000];
int bb[2000];
int c[20000];
scanf("%s%s",a,b);
memset(bb,0,sizeof(bb));
memset(aa,0,sizeof(aa));
memset(c,0,sizeof(c));
int j=0;
int la=strlen(a);
int lb=strlen(b);
for(int i=la-1;i>=0;i--)
{
aa[j]=a[i]-'0';
j++;
}
j=0;
for(int i=lb-1;i>=0;i--)
{
bb[j]=b[i]-'0';
j++;
}
j=0;
///////倒序完成.
int n=max(la,lb);
for(int i=0;a[i]!='\0';i++)
{
c[i]+=aa[i];
}
for(int i=0;b[i]!='\0';i++)
{
c[i]+=bb[i];
}
for(int i=0;i<n;i++)
{
if(c[i]>=10)
{
c[i+1]+=c[i]/10;
c[i]=c[i]%10;//此处位子不能颠倒.
}
}
printf("Case %d:\n",++kase);
if(c[n]==0)
{
printf("%s + %s = ",a,b);
for(int i=n-1;i>=0;i--)
{
printf("%d",c[i]);
}
printf("\n");
if(t!=0)
printf("\n");
continue;
}
printf("%s + %s = ",a,b);
for(int i=n;i>=0;i--)
{
printf("%d",c[i]);
}
printf("\n");
if(t!=0)
printf("\n");
}
}