A + B Problem II
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 188211 Accepted Submission(s): 35956
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
Author
Ignatius.L
题意:
给出 T (1 ~ 20)个case,后给出两个数a,b,每个数的长度最多1000位,求两个数加和按要求格式输出。
思路:
输入的顺序是从高位向地位输入,故计算的时候从 n -> 0 计算,并且考虑进位情况。考虑到数的输入输出情况,故开 char 型数组比较方便,计算的时候相应减去字符 0 即可。
两个数的长度可能不一致,故先对其,前补0再计算,输出的时候不输出前导0,每个case之间要空一行,最后一个case不需要空行,大概注意这些就可以AC了。
AC:
#include<stdio.h>
#include<string.h>
#include<algorithm>
using namespace std;
int main()
{
int n,time = 0;
scanf("%d",&n);
while(n--)
{
int CIN = 0,len_a,len_b,len_sum;
char a[1005],b[1005],sum[1005],temp[1005],temp_a[1005],temp_b[1005];
time++;
scanf("%s%s",a,b);
len_a = strlen(a);
len_b = strlen(b);
len_sum = max(len_a,len_b);
strcpy(temp_a,a);
strcpy(temp_b,b);
if(len_a > len_b)
{
int idex_b = 0,i;
for(i = 0;i < len_a - len_b;i++)
temp[i] = '0';
for(i;i < len_a;i++,idex_b++)
temp[i] = b[idex_b];
for(i = 0;i < len_a;i++)
b[i] = temp[i];
b[i] = '\0';
}
if(len_b > len_a)
{
int idex_a = 0,i;
for(i = 0;i < len_b - len_a;i++)
temp[i] = '0';
for(i;i < len_b;i++,idex_a++)
temp[i] = a[idex_a];
for(int i = 0;i < len_b;i++)
a[i] = temp[i];
a[i] = '\0';
}
for(int i = len_sum - 1;i >= 0;i--)
{
int ans = (a[i] + b[i] - '0' - '0' + CIN);
sum[i] = ans % 10 + '0';
CIN = ans / 10;
}
sum[len_sum] = '\0';
printf("Case %d:\n",time);
printf("%s + %s = ",temp_a,temp_b);
if(CIN) printf("%d",CIN);
puts(sum);
if(n) printf("\n");
}
return 0;
}