题解 | a+b 自定义大整形加法

a+b

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

//本题只要求两个高精度整数的加法,因此只需用到上面模板中关于构造、赋值、输入、输出和加法的部分即可
#include <iostream>
#include <cstdio>
#include <iterator>
#include <string>
#include <cstring>
using namespace std;

const int maxn= 10000;

struct biginteger{
    int digit[maxn];
    int length;
    biginteger(); //构造
    biginteger operator=(string str);   //赋值
    biginteger operator+(const biginteger& b);  //相加
    friend istream& operator>>(istream& in,biginteger& x);//输入  
    friend ostream& operator<<(ostream& out,biginteger& x);//输出
};

istream& operator>>(istream& in,biginteger& x){
    string str;
    in>>str;
    x=str;
    return in;
}

ostream& operator<<(ostream& out ,const biginteger& x){
    for(int i=x.length-1;i>=0;i--){
        out<<x.digit[i];
    }
    return out;
}

biginteger::biginteger(){
    memset(digit, 0, sizeof(digit)); //构造
    length = 0;
}
biginteger biginteger::operator=(string str){          //赋值
    memset(digit, 0, sizeof(digit));
    length = str.size();
    for (int i=0; i<length; i++) {
        digit[i]=str[length-i-1]-'0';
    }
    return *this;
}
biginteger biginteger::operator+(const biginteger& b){  //相加
    biginteger answer;
    int carry = 0;
    for(int i=0;i<length||i<b.length;i++){
        int current = carry + digit[i]+b.digit[i]; //和正常计算一样,先算当前位,再算进位
        carry = current/10;
        answer.digit[answer.length++] = current%10;  //将当前位存入答案
    }
    if(carry){
        answer.digit[answer.length++] = carry;
    }
    return answer;

}
int main(){
    biginteger a;
    biginteger b;
    while(cin>>a>>b){
        cout<<a+b<<endl;
    }
    return 0;
}

大整形(高精度整数) 文章被收录于专栏

对于使用Java,本节的内容对你毫无用处,因为Java类库中内置了BigInteger类,只需查阅相关资料了解其用法 对于使用C/C++的读者,在这里为读者提供高精度整数的模板,按照模板敲就好了,需要注意的是,模板只适用于正整数的运算,小数减大数的运算会出错。模板包括加、减、乘、除、取模、输入、输出等一系列操作的实现,机试时需要用到什么运算,只需要&ldquo;敲&rdquo;对应的操作即可,无须写完整个模板。

全部评论

相关推荐

评论
点赞
收藏
分享

创作者周榜

更多
正在热议
更多
牛客网
牛客企业服务