A + B Problem II
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 436132 Accepted Submission(s): 84861
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
本题是一道大数加法题
emmmmmm具体过程请看其他大佬的博客,本人只是一小白嘤嘤嘤
说一下我的理解
当你输入很大很大的数 long long 也是存不下的,这时我们就需要用上字符串
建立两个字符数组,把要想加的数用字符数组存起来,然后每位再转换为整型
分别量一下长度 再建立一个int型数组,长度取这两个字符数组中长的。然后我们再从后往前遍历,如果这位上两个字符数组都有数字,就相加落到int数组里,否则直接落下
最后再从后往前遍历一下int数组,如果这位数字大于10,就往前进位
最后再循环输出int数组的元素就ok了
其实就是模拟小学手写的加法,字丑请见谅=.=
最后附上这题的AC代码:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdbool.h>
#include <ctype.h>
#include <math.h>
#define PI acos(-1)
int main()
{
char add1[1005],add2[1005];
int result[1005];
int length_add1,length_add2,length_result,test_num,lc;
int i,j,k;
while(scanf("%d",&test_num) != EOF)
{
for(i = 1; i <= test_num; i++)
{
scanf("%s%s",add1,add2);
length_add1 = strlen(add1);
length_add2 = strlen(add2);
memset(result, 0, sizeof(result));
printf("Case %d:\n",i);
printf("%s + %s = ",add1,add2);
for(j = 0; j < length_add1; j++)
add1[j] -= '0';
for(j = 0; j < length_add2; j++)
add2[j] -= '0';
length_result = length_add1 > length_add2? length_add1 : length_add2;
lc = length_result - 1;
for(j = length_add1 - 1, k = length_add2 - 1; ; j--, k--)
{
if(j >= 0 && k >= 0)
result[lc--] = add1[j] + add2[k];
else if(j >= 0)
result[lc--] = add1[j];
else if(k >= 0)
result[lc--] = add2[k];
else
break;
}
for(j = length_result - 1; j > 0; j--)
{
if(result[j] >= 10)
{
result[j - 1] += result[j] / 10;
result[j] = result[j] % 10;
}
}
for(j = 0; j < length_result; j++)
printf("%d",result[j]);
printf("\n");
if(i != test_num)
printf("\n");
}
}
return 0;
}
写于我老姨家