题解 | #a+b#

a+b

http://www.nowcoder.com/practice/4c39c984ea3848b48e111b8e71ec1dd4

#include<iostream>
#include<cstdio>
#include<cstring>
#include<string>
using namespace std;
const int MAXN = 10000;
struct BigInteger {
    int digit[MAXN];
    int length;
    BigInteger();
    BigInteger(int x);
    BigInteger(string str);
    BigInteger(const BigInteger& b);
    BigInteger operator=(int x);
    BigInteger operator=(string str);
    BigInteger operator=(const BigInteger& b);
    BigInteger operator+(const BigInteger& b);
    friend istream& operator>>(istream& cin, BigInteger& b);
    friend ostream& operator<<(ostream& cout, const BigInteger& b);
};
BigInteger::BigInteger() {
    memset(digit, 0, sizeof(digit));
    length = 0;
}
BigInteger::BigInteger(int x) {
    memset(digit, 0, sizeof(digit));
    length = 0;
    if (!x) {
        digit[length++] = x;
    }
    while (x) {
        digit[length++] = x % 10;
        x /= 10;
    }
}
BigInteger::BigInteger(string str) {
    memset(digit, 0, sizeof(digit));
    length = str.size();
    for (int i = 0; i < length; ++i) {
        digit[i] = str[length - 1 - i] - '0';
    }
}
BigInteger::BigInteger(const BigInteger& b) {
    memset(digit, 0, sizeof(digit));
    length = b.length;
    for (int i = 0; i < length; ++i) {
        digit[i] = b.digit[i];
    }
}
BigInteger BigInteger::operator=(int x) {
    memset(digit, 0, sizeof(digit));
    length = 0;
    if (!x) {
        digit[length++] = x;
    }
    while (x) {
        digit[length++] = x % 10;
        x /= 10;
    }
    return *this;
}
BigInteger BigInteger::operator=(string str) {
    memset(digit, 0, sizeof(digit));
    length = str.size();
    for (int i = 0; i < length; ++i) {
        digit[i] = str[length - 1 - i] - '0';
    }
    return *this;
}
BigInteger BigInteger::operator=(const BigInteger& b) {
    memset(digit, 0, sizeof(digit));
    length = b.length;
    for (int i = 0; i < length; ++i) {
        digit[i] = b.digit[i];
    }
    return *this;
}
BigInteger BigInteger::operator+(const BigInteger& b) {
    BigInteger ans;
    int carry = 0;
    for (int i = 0; i < length || i < b.length; ++i) {
        ans.digit[ans.length++] = (digit[i] + b.digit[i] + carry) % 10;
        carry = (digit[i] + b.digit[i] + carry) / 10;
    }
    if (carry) {
        ans.digit[ans.length++] = carry;
    }
    return ans;
}
istream& operator>>(istream& cin, BigInteger& b) {
    string in;
    cin >> in;
    b = in;
    return cin;
}
ostream& operator<<(ostream& cout, const BigInteger& b) {
    for (int i = b.length - 1; i >= 0; --i) {
        cout << b.digit[i];
    }
    return cout;
}
int main() {
    BigInteger a;
    BigInteger b;
    while (cin >> a >> b) {
        cout << a + b << endl;
    }
    return 0;
}

全部评论

相关推荐

09-12 11:55
已编辑
湖南工商大学 Java
那一天的Java_J...:这种一堆问题的,别去
点赞 评论 收藏
分享
用微笑面对困难:只要你保证项目和获奖都是真的就行尤其是“对战,总负责人”啊这些套职,基本上队员,打杂的都这么写
点赞 评论 收藏
分享
评论
1
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务