转载请注明出处:優YoU http://user.qzone.qq.com/289065406/blog/1299062368
提示:就是多个大数相加的问题= =
1 //Memory Time
2 //184K 0MS
3
4 #include<iostream>
5 #include<cstring>
6 using namespace std;
7
8 const int large=1000;
9 char sum_temp[large];
10 char digit_temp[large];
11
12 int plus(int j,int carry_bit)
13 {
14 int count;
15 count=(sum_temp[j]-'0')+(digit_temp[j]-'0')+carry_bit;
16 sum_temp[j]=count%10+'0';
17 if(count<10)
18 return 0;
19 else
20 return 1;
21 }
22
23 int main(void)
24 {
25 int length,i,j,k;
26 int max=0,carry_bit=0;
27 char digit[large],sum[large];
28
29 memset(sum_temp,'0',sizeof(sum_temp));
30
31 for(i=-1;strcmp(digit,"0");)
32 {
33 i++;
34 gets(digit);
35 length=strlen(digit)-1;
36
37 memset(digit_temp,'0',sizeof(digit_temp));
38
39 for(k=0,j=length;j>=0;--j,++k)
40 digit_temp[k]=digit[j]; //倒置
41 if(max<length)
42 max=length;
43 for(carry_bit=0,j=0;j<=max;j++) //每两个长数相加一次进位必须初始化进位值
44 carry_bit=plus(j,carry_bit);
45 if(carry_bit==1) //最高位进位检查
46 sum_temp[++max]='1';
47 for(i=max,j=0;i>=0;--i,++j)
48 {
49 if(i==max&&sum_temp[i]=='0') //检查并消去高位0
50 {
51 --max;
52 continue;
53 }
54 sum[j]=sum_temp[i]; //倒置
55 }
56 sum[j]='\0'; //末尾添加结束符
57 }
58 cout<<sum<<endl;
59 return 0;
60 }