Skip to content

11014: 【原1014】高精度加法

题目

题目描述

author: 韩立 原OJ链接:https://acm.sjtu.edu.cn/OnlineJudge-old/problem/1014

Description

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

Input Format

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

\(0 \leq a , b \leq 10^{100000}\)。

Output Format

输出只有一行,a+b。

Sample Input

1234
1111111111

Sample Output

1111112345

FineArtz's solution

/* 高精度加法 */
#include <iostream>
#include <string>
using namespace std;

class BigInt{
    friend BigInt operator +(const BigInt&, const BigInt&);
    friend ostream& operator <<(ostream &, const BigInt&);
public:
//constructor
    BigInt(string);

    int getl() const { return len; }
private:
    short data[100005];
    int len;
};

BigInt::BigInt(string s){
    len = s.size();
    for (int i = 1; i <= len; ++i)
        data[i] = s[len - i] - '0';
}

BigInt operator +(const BigInt &a, const BigInt &b){
    BigInt ans("");
    int l = (a.getl() > b.getl() ? a.getl() : b.getl());
    ans.len = l;
    for (int i = 1; i <= l; ++i)
        ans.data[i] = a.data[i] + b.data[i];
    int i = 1;
    while (i <= l + 1){
        if (ans.data[i] >= 10){
            ans.data[i++] -= 10;
            ++ans.data[i];
        }
        else ++i;
    }
    ans.len = i;
    while (ans.data[ans.len] == 0) --ans.len;
    return ans;
}
ostream& operator <<(ostream &os, const BigInt &a){
    for (int i = a.len; i >= 1; --i)
        os << a.data[i];
    return os;
}

int main(){
    string s1, s2;
    cin >> s1 >> s2;
    BigInt a(s1), b(s2);
    cout << a + b << endl;
    return 0;
}

yyong119's solution

#include <iostream>
#include <cstring>
int a[100001],b[100001],c[100001];
char p[100000],q[100000];
int i,length;
int main(){
    using namespace std;
    cin>>p>>q;
    for (i=0; i<=strlen(p)-1; i++) a[strlen(p)-i]=int(p[i]-'0');
    for (i=0; i<=strlen(q)-1; i++) b[strlen(q)-i]=int(q[i]-'0');
    if (strlen(p)>=strlen(q)) length=strlen(p);
        else length=strlen(q);
    for (i=1; i<=length; i++){
        c[i]+=a[i]+b[i];
        c[i+1]+=c[i]/10; c[i]=c[i]%10;
    }
    if (c[length+1]) length++;
    for (i=length; i>=1; i--) cout<<c[i];
    return 0;
}