用字符串模拟大数,只需注意进位,使用了栈。
代码:
1 #include<stdio.h> 2 #include<string.h> 3 char A[99999]; 4 char B[99999]; 5 char sum[99999]="0"; 6 void add() 7 { 8 int top1=0,top2=0,len1,len2,len,top=0,i,j,temp; 9 for(top1=0;A[top1]!='\0';top1++); 10 for(top2=0;B[top2]!='\0';top2++); 11 printf("%d %d\n",top1,top2); 12 len=top1+top2; 13 top=len; 14 sum[top]='\0'; 15 if(top1>top2) j=1; 16 else if(top1==top2) j=0; 17 else j=-1; 18 top1--; 19 top2--; 20 top--; 21 int a,b; 22 temp=0; 23 while(top1>=0&&top2>=0) 24 { 25 a=A[top1]-'0'; 26 b=B[top2]-'0'; 27 temp+=a+b; 28 sum[top]=temp%10+'0'; 29 temp/=10; 30 top1--; 31 top2--; 32 top--; 33 } 34 if(j==1) 35 { 36 while(top1>=0) 37 { 38 a=A[top1]-'0'; 39 temp+=a; 40 sum[top]=temp%10+'0'; 41 temp/=10; 42 top1--; 43 top--; 44 } 45 if(temp!=0) 46 { 47 sum[top]=temp+'0'; 48 top--; 49 } 50 } 51 else if(j==-1) 52 { 53 while(top2>=0) 54 { 55 a=B[top2]-'0'; 56 temp+=a; 57 sum[top]=temp%10+'0'; 58 temp/=10; 59 top2--; 60 top--; 61 } 62 if(temp!=0) 63 { 64 sum[top]=temp+'0'; 65 top--; 66 } 67 } 68 else if(j==0) 69 { 70 if(temp!=0) 71 { 72 sum[top]=temp+'0'; 73 top--; 74 } 75 } 76 for(i=top+1,j=0;i<len;i++) 77 { 78 sum[j]=sum[i]; 79 j++; 80 } 81 sum[j]='\0'; 82 return; 83 } 84 int main() 85 { 86 gets(A); 87 gets(B); 88 add(); 89 puts(sum); 90 return 0; 91 }