大数相加

大输相加问题
A + B Problem II
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

解题思路:
int类型(范围:2^31 - 1)超过9位数不适用
long long类型(范围:2^64 - 1)超过19位不适用
显然两种类型都不适用该题,直接当作大数处理,将输入的两个数当作字符数组,将其反转后的每一位当作数字相加,数字大于9的,向后一位进位1,最后将相加的结果反转输出。注意要记录数组的大下,以便输出结果。

代码如下:
#include<cstdio>
#include<cstring>
#include<iostream>
#include<algorithm>
#include<cstring>
#include<math.h>
using namespace std;
#define maxn 1000 + 10
int a[maxn],b[maxn];
char s1[maxn],s2[maxn];
int main(){
    int n,j;
    scanf("%d",&n);
    for(int j = 1; j <= n; j++){
        memset(a,0,sizeof(a));
        memset(b,0,sizeof(b));
        cin >> s1 >> s2;
        int len1 = strlen(s1);
        int len2 = strlen(s2);
        int k1 = 0,k2=0;
        for(int i = len1-1; i >= 0; i--){//反转s1到a
            a[k1++] = s1[i] - '0';
        }
        for(int i = len2 - 1; i >= 0; i--){//反转s2到b
            b[k2++] = s2[i] - '0';
        }
        int t = max(k1,k2);
        int c = 0;
        for(int i = 0;i < t; i++){//a[i]+b[i],注意进位
            a[i] += b[i];
            c++;
        //处理进位
            if(a[i]>9){
                a[i] %= 10;
                a[i+1]++;
            }
        }
    //结果打印
        printf("Case %d:\n%s + %s = ",j,s1,s2);
        for(int i = c-1; i >= 0; i--){
            printf("%d",a[i]);
        }
    //格式处理,结果间空一行
        printf("\n");
        if(j != n){
            printf("\n");
        }
    }
    return 0;
}

posted @ 2018-07-17 18:29  半忧夏  阅读(95)  评论(0)    收藏  举报