递归 - webdancer's Blog
递归
对于递归算法,基本没有什么理解,但是有时候递归的用处还是很多的。记录几个例子。
1.用递归的方法,写函数itoa(n,s),将整数转为字符串。
int i; void itoa(int n,char s[]){ if(n/10) itoa(n/10,s); else{ i=0; if(n<0) s[i++]='-'; } s[i++]=n%10+'0'; s[i]='\0'; }
2.用递归方法,写函数reverse1(s),将字符串倒置。
void swap(char *i,char *j){ char tmp; tmp=*i; *i=*j; *j=tmp; } void reverse0(char s[],int i,int n){ int j; j=n-(i+1); if(i<j){ swap(&s[i],&s[j]); reverse0(s,++i,n); } } void reverse1(char s[]){ reverse0(s,0,strlen(s)); }
3.Fibonacci数列的递归实现。
int fibonacci(int n){ if(n<2) return n; else return fibonacci(n-1)+fibonacci(n-2); }
4.求最大公约数。
int gcd(int x,int y){ if(y==0) return x; else return gcd(y,x%y); }
递归:函数不断调用自身,直到遇到结束条件停止。
代码简洁,容易理解。但是,递归过程会消耗大量的栈空间,不适合嵌入式系统或者内核态编程。
2022年8月24日 17:59
Kerala Plus Two Old Important Model Question Paper 2023 PDF 2023 is Released in Online Mode. Kerala DHSE Board 11th Arts, Science and Commerce Group Important Model Question Paper 2023 Attachments are Available on This Page. Kerala Plus Two Question Paper 2023 Important Model Question Paper 2023 are an Important Two for the Students to Getting High Scores in the Board Examinations. Kerala Plus Two Malayalam, English, Computer Science, Computer Application, Hindi, Chemistry, Statistics, Economics, History, Geology, Physics, Maths, Tamil, Kannada and Other Subjects Last Year Important Model Question Paper 2023 are Download on the Official Website. Kerala State Board Important Model Question Paper 2023 PDF are Given Below.