杭电1297Children’s Queue(大整数加法)

View Code
 1 //杭电1297Children’s Queue
 2 //关于大整数加法
 3 #include<stdio.h>
 4 #include<string.h>
 5 
 6 char* add(char* s1,char* s2)//用指针定义变量
 7 {
 8     int len1,len2,i,j,k,p;
 9     int a[1009],b[1009];
10     int max;
11     char s3[1009];
12     len1=strlen(s1);
13     len2=strlen(s2);
14     max=len1;
15     if(max<len2)
16         max=len2;
17     memset(a,0,sizeof(a));
18     memset(b,0,sizeof(b));
19     k=0;
20     for(i=len1-1;i>=0;i--)//将字符串s1[]中的每一个字符转变成整数,并将每一个位的整数存入数组中
21         a[k++]=s1[i]-'0';
22     p=0;
23     for(j=len2-1;j>=0;j--)//同上,为了便于下一步相加
24         b[p++]=s2[j]-'0';
25     for(i=0;i<max;i++)//将对应位上的整数相加,并存入a[];
26     {
27         a[i]+=b[i];
28         if(a[i]>=10)
29         {
30             a[i]=a[i]-10;
31             a[i+1]++;
32         }
33     }
34     if(a[max]!=0)max++;
35     for(i=max-1;i>=0;i--)
36         s3[i]=a[i]+'0';
37     s3[max]='\0';
38     strrev(s3);
39     return s3;
40 }
41 
42 
43 
44 int main()
45 {
46     int n,i;
47     char f[1009][1009];//由于每个n对应的都是一个字符串,故存为二位字符;
48     char* p;
49     strcpy(f[0],"1");//将f[0],f[1],f[2],f[3]初始为字符串
50     strcpy(f[1],"1");
51     strcpy(f[2],"2");
52     strcpy(f[3],"4");
53     for(i=4;i<1001;i++)
54     {
55         p=add(f[i-1],f[i-2]);
56         strcpy(f[i],p);
57         p=add(f[i],f[i-4]);
58         strcpy(f[i],p);
59     }
60     while(scanf("%d",&n)!=-1)
61     {
62         puts(f[n]);
63     }
64     return 0;
65 }

先用递推找出规律,f[n]=f[n-1]+f[n-2]+f[n-4];在大整数相加过程中,返回值为字符串,用指针

原文地址:https://www.cnblogs.com/zlyblog/p/2585974.html