您的位置:首页 > 其它

大数加法

2017-02-03 17:39 148 查看
基准时间限制: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<cstdio>
#include<cstring>
int la,lb,lc,qa=1,qb=1;
int a[10010],b[10010],c[10010];
char ch[10010],cn[10010];
bool p;
bool bj(){
if(la>lb) return 1;
if(la<lb) return 0;
for(int i=0;i<la;i++){
if(ch[i+1-qa]>cn[i+1-qb]) return 1;
if(ch[i+1-qa]<cn[i+1-qb]) return 0;
}
return 1;
}
void add(){
lc=la;
for(int i=0;i<la;i++){
c[i]+=a[i]+b[i];
if(c[i]>9){
c[i+1]++;
c[i]%=10;
if(i+1==la) lc++;
}
}
}
void cut(){
lc=la;
for(int i=0;i<la;i++){
c[i]+=a[i]-b[i];
if(c[i]<0){
a[i+1]--;
c[i]+=10;
}
}
while(!c[lc-1]&&lc>1) lc--;
}
int main(){
scanf("%s%s",&ch,&cn);
la=strlen(ch);lb=strlen(cn);
if(ch[0]=='-') la--,qa--;
if(cn[0]=='-') lb--,qb--;
p=bj();
if(p){
for(int i=0;i<la;i++) a[i]=ch[la-i-qa]-'0';
for(int i=0;i<lb;i++) b[i]=cn[lb-i-qb]-'0';
}
else{
for(int i=0;i<lb;i++) a[i]=cn[lb-i-qb]-'0';
for(int i=0;i<la;i++) b[i]=ch[la-i-qa]-'0';
lc=la;la=lb;lb=lc;
}
if((ch[0]=='-'&&cn[0]!='-')||(ch[0]!='-'&&cn[0]=='-')) cut();
else add();
if((ch[0]==cn[0]=='-'||(p&&ch[0]=='-')||(p==0&&cn[0]=='-'))&&(lc>1||c[0])) printf("-");
for(int i=lc-1;i>=0;i--) printf("%d",c[i]);
printf("\n");
return 0;
}


附带压位优化的版本:

#include<cstdio>
#include<cstring>
int la,lb,lc,qa=1,qb=1;
int a[10010],b[10010],c[10010];
char ch[10010],cn[10010];
bool p;
bool bj(){
if(la>lb) return 1;
if(la<lb) return 0;
for(int i=0;i<la;i++){
if(ch[i+1-qa]>cn[i+1-qb]) return 1;
if(ch[i+1-qa]<cn[i+1-qb]) return 0;
}
return 1;
}
void add(){
lc=la;
for(int i=0;i<=la;i++){
c[i]+=a[i]+b[i];
if(c[i]>99999999){
c[i+1]++;
c[i]%=100000000;
if(i+1==la) lc++;
}
}
}
void cut(){
lc=la;
for(int i=0;i<=la;i++){
c[i]+=a[i]-b[i];
if(c[i]<0){
a[i+1]--;
c[i]+=100000000;
}
}
}
int main(){
scanf("%s%s",&ch,&cn);
la=strlen(ch);lb=strlen(cn);
if(ch[0]=='-') la--,qa--;
if(cn[0]=='-') lb--,qb--;
p=bj();
if(p){
for(int i=0;i<la;i++) a[i]=ch[la-i-qa]-'0';
for(int i=0;i<lb;i++) b[i]=cn[lb-i-qb]-'0';
}
else{
for(int i=0;i<lb;i++) a[i]=cn[lb-i-qb]-'0';
for(int i=0;i<la;i++) b[i]=ch[la-i-qa]-'0';
lc=la;la=lb;lb=lc;
}
for(int i=0;i<=la/8;i++)
for(int j=0,k=1;j<8;j++,k*=10) c[i]+=a[8*i+j]*k;
for(int i=0;i<la;i++) a[i]=0;
for(int i=0;i<la;i++){a[i]=c[i];c[i]=0;}
while(!a[la]) la--;
for(int i=0;i<=lb/8;i++)
for(int j=0,k=1;j<8;j++,k*=10) c[i]+=b[8*i+j]*k;
for(int i=0;i<lb;i++) b[i]=0;
for(int i=0;i<lb;i++){b[i]=c[i];c[i]=0;}
while(!b[lb]) lb--;
if((ch[0]=='-'&&cn[0]!='-')||(ch[0]!='-'&&cn[0]=='-')) cut();
else add();
if((ch[0]==cn[0]=='-'||(p&&ch[0]=='-')||(p==0&&cn[0]=='-'))&&(lc>1||c[0])) printf("-");
while(!c[lc]&&lc>0) lc--;
for(int i=lc;i>=0;i--){
if(i!=lc) for(int j=10000000;j>c[i]&&j>1;j/=10) printf("0");
printf("%d",c[i]);
}
printf("\n");
return 0;
}


坑爹啊,加法为什么要有负数。

题目来源:51Nod
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: