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;
}