HDU-1002(C語言)大數加法
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;
}
寫於我老姨家