51Nod-1005 大数加法

1005 大数加法
基准时间限制:1 秒 空间限制:131072 KB 分值: 0 难度:基础题 收藏 关注
给出2个大整数A,B,计算A+B的结果。
Input
第1行:大数A
第2行:大数B
(A,B的长度 <= 10000 需注意:A B有可能为负数)
Output
输出A + B
Input示例
68932147586
468711654886
Output示例
537643802472

#include<bits/stdc++.h>
using namespace std;
#define Max 10010
struct Node
{
    int b[Max];
    int length;
    int f;
    Node(){memset(b,0,sizeof(b));}
    Node(char *s){
        memset(b,0,sizeof(b));
        if(s[0]=='-'){
            f=1;
            s++;
        }
        else
            f=0;
        int i=0;
        while(s[i]!='\0'){
            b[i]=s[i]-'0';
            i++;
        }
        length=i;
        for(int i=0,j=length-1;i<j;i++,j--)
            swap(b[i],b[j]);
    }
    bool operator <(const Node &t) const{
        if(this->length==t.length){
            for(int i=t.length-1;i>=0;i--){
                if(this->b[i]<t.b[i])
                    return true;
                else if(this->b[i]>t.b[i])
                    return false;
            }
        }
        return this->length<=t.length;
    }
    Node operator + (const Node &t) const{
        Node ans;
        if(t.f==this->f){
            ans.f=this->f;
            int length=max(t.length,this->length);
            ans.length=length;
            for(int i=0;i<length;i++){
                ans.b[i]+=this->b[i]+t.b[i];
                ans.b[i+1]+=ans.b[i]/10;
                ans.b[i]%=10;
            }
            if(ans.b[length]!=0)
                ans.length++;
            while(ans.length>1&&ans.b[ans.length-1]==0)
                ans.length--;
        }
        else {
            if(t<(*this))
                ans=(*this-t);
            else
                ans=t-(*this);
        }
        return ans;
    }
    Node operator - (const Node &t) const{
        Node ans;
        ans.f=this->f;
        int length=this->length;
        ans.length=length;
        for(int i=0;i<length;i++){
            ans.b[i]+=this->b[i]-t.b[i];
            if(ans.b[i]<0){
                ans.b[i]+=10;
                ans.b[i+1]--;
            }
        }
        while(ans.length>1&&ans.b[ans.length-1]==0)
            ans.length--;
        return ans;
    }
};

char str[Max];
int main(int argc, char const *argv[])
{
    cin>>str;
    Node a(str);
    cin>>str;
    Node b(str);
    Node ans=a+b;
    if(ans.f)
        cout<<"-";
    for(int i=ans.length-1;i>=0;i--)
        cout<<ans.b[i];
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值