上海交大OJ 高精度整数

1014. 高精度加法

Description

输入2个整数a和b,输出a+b。

Input Format

输入有两行,第一行a,第二行b。

0≤a,b≤10 100000  0≤a,b≤10100000 。

Output Format

输出只有一行,a+b。

Sample Input

1234
1111111111

Sample Output

1111112345
#include <cstdio>
#include <iostream>
#include <cstring>
#include <vector>

using namespace std;

int main(int argc, char const *argv[]) {
    string a,b;
    cin >> a >> b;

    //sa - a转化成的数组  sb - b转化成的数组
    char sa[1000005];
    char sb[1000005];

    //进行字符串 - 字符数组转化
    strcpy(sa,a.c_str());
    strcpy(sb,b.c_str());

    //用于存储计算结果
    vector<int> u;

    //标志是否进位
    int t = 0;
    //当上面的数笔下面的数长时
    if(a.length() > b.length()){
        for(int i = a.length(),j = b.length();i > 0;i--,j--){
            //当此位有两个数时
            if(j > 0){
                //当不进位的时候
                if((sa[i - 1] - '0') + (sb[j - 1] - '0') + t < 10){
                    //printf("%d\n",(sa[i] - '0') + (sb[j] - '0') + t);
                    //同位相加入栈
                    u.push_back((sa[i - 1] - '0') + (sb[j - 1] - '0') + t);
                    t = 0;
                }else{//当进位时
                    //printf("%d\n",(sa[i] - '0') + (sb[j] - '0') + t - 10);
                    u.push_back((sa[i - 1] - '0') + (sb[j - 1] - '0') + t - 10);
                    t = 1;
                }
            }else{//当此位只剩一个数时
                //当不进位的时候
                if((sa[i - 1] - '0') + t < 10){
                    //同位相加入栈
                    u.push_back((sa[i - 1] - '0') + t);
                    t = 0;
                }else{//当进位时
                    //printf("%d\n",(sa[i] - '0') + (sb[j] - '0') + t - 10);
                    u.push_back((sa[i - 1] - '0') + t - 10);
                    t = 1;
                }
            }
        }
        if(t > 0)u.push_back(t);
    }
    else{//当下面数比上面长时
        for(int i = a.length(),j = b.length();j > 0;i--,j--){
            if(i > 0){
                if((sa[i - 1] - '0') + (sb[j - 1] - '0') + t < 10){
                    //printf("%d\n",(sa[i] - '0') + (sb[j] - '0') + t);
                    u.push_back((sa[i - 1] - '0') + (sb[j - 1] - '0') + t);
                    t = 0;
                }else{
                    //printf("%d\n",(sa[i] - '0') + (sb[j] - '0') + t - 10);
                    u.push_back((sa[i - 1] - '0') + (sb[j - 1] - '0') + t - 10);
                    t = 1;
                }
            }else{
                if((sb[j - 1] - '0') + t < 10){
                    //同位相加入栈
                    u.push_back((sb[j - 1] - '0') + t);
                    t = 0;
                }else{//当进位时
                    //printf("%d\n",(sa[i] - '0') + (sb[j] - '0') + t - 10);
                    u.push_back((sb[j - 1] - '0') + t - 10);
                    t = 1;
                }
            }
        }
        if(t > 0)u.push_back(t);
    }
    //出栈输出结果
    while (!u.empty()) {

        printf("%d",u.back());

        u.pop_back();
    }

    return 0;
}

 

猜你喜欢

转载自blog.csdn.net/WX_1218639030/article/details/84032642