码迷,mamicode.com
首页 > 其他好文 > 详细

大数加法

时间:2017-02-03 18:32:18      阅读:222      评论:0      收藏:0      [点我收藏+]

标签:print   bsp   amp   std   style   log   main   har   targe   

给出2个大整数A,B,计算A+B的结果。
 
Input
第1行:大数A
第2行:大数B
(A,B的长度 <= 10000 需注意:A B有可能为负数)
Output
输出A + B
Input示例
68932147586
468711654886
Output示例
537643802472
代码实现:
 1 #include<cstdio>
 2 #include<cstring>
 3 int la,lb,lc,qa=1,qb=1;
 4 int a[10010],b[10010],c[10010];
 5 char ch[10010],cn[10010];
 6 bool p;
 7 bool bj(){
 8     if(la>lb) return 1;
 9     if(la<lb) return 0;
10     for(int i=0;i<la;i++){
11         if(ch[i+1-qa]>cn[i+1-qb]) return 1;
12         if(ch[i+1-qa]<cn[i+1-qb]) return 0;
13     }
14     return 1;
15 }
16 void add(){
17     lc=la;
18     for(int i=0;i<la;i++){
19         c[i]+=a[i]+b[i];
20         if(c[i]>9){
21             c[i+1]++;
22             c[i]%=10;
23             if(i+1==la) lc++;
24         }
25     }
26 }
27 void cut(){
28     lc=la;
29     for(int i=0;i<la;i++){
30         c[i]+=a[i]-b[i];
31         if(c[i]<0){
32             a[i+1]--;
33             c[i]+=10;
34         }
35     }
36     while(!c[lc-1]&&lc>1) lc--;
37 }
38 int main(){
39     scanf("%s%s",&ch,&cn);
40     la=strlen(ch);lb=strlen(cn);
41     if(ch[0]==-) la--,qa--;
42     if(cn[0]==-) lb--,qb--;
43     p=bj();
44     if(p){
45         for(int i=0;i<la;i++) a[i]=ch[la-i-qa]-0;
46         for(int i=0;i<lb;i++) b[i]=cn[lb-i-qb]-0;
47     }
48     else{
49         for(int i=0;i<lb;i++) a[i]=cn[lb-i-qb]-0;
50         for(int i=0;i<la;i++) b[i]=ch[la-i-qa]-0;
51         lc=la;la=lb;lb=lc;
52     }
53     if((ch[0]==-&&cn[0]!=-)||(ch[0]!=-&&cn[0]==-)) cut();
54     else add();
55     if((ch[0]==cn[0]==-||(p&&ch[0]==-)||(p==0&&cn[0]==-))&&(lc>1||c[0])) printf("-");
56     for(int i=lc-1;i>=0;i--) printf("%d",c[i]);
57     printf("\n"); 
58     return 0;
59 }

题目来源:51Nod

大数加法

标签:print   bsp   amp   std   style   log   main   har   targe   

原文地址:http://www.cnblogs.com/J-william/p/6363129.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!