1.递归和非递归分别实现求第n个斐波那契数
int FibRec(int n) {
if (n < 1) {
return -1;
}
if (n == 1 || n == 2) {
return 1;
}
return FibRec(n - 1) + FibRec(n - 2);
}
int FibNoRec(int n) {
if (n < 1) {
return -1;
}
int curr, prev1 = 1, prev2 = 1;
for (int i = 2; i < n; ++i) {
curr = prev1 + prev2;
prev2 = prev1;
prev1 = curr;
}
return curr;
}
2.递归实现n^k
int _Pow(int n, int k) {
if (k == 0) {
return 1;
}
return n * _Pow(n, k - 1);
}
double Pow(int n, int k) {
if (n == 0) {
return 0;
}
if (k < 0) {
k = 0 - k;
return (double)1 / _Pow(n, k);
}
return _Pow(n, k);
}
3.递归计算n的各位之和
int DigitSum(int n) {
if (n < 0) {
return -1;
}
if (n == 0) {
return 0;
}
return n % 10 + DigitSum(n / 10);
}
4.递归逆置字符串
void reverse_string(char * string) {
int len;
if ((len = StrLenNoRec(string)) == 0) {
return;
}
char ch = *string;
*string = *(string + len - 1);
*(string + len - 1) = '\0';
reverse_string(string + 1);
*(string + len - 1) = ch;
}
5.递归和非递归分别实现strlen
int StrLenRec(char* str) {
if (*str == '\0') {
return 0;
}
return 1 + StrLenRec(++str);
}
int StrLenNoRec(char* str) {
int len = 0;
while (*str != '\0') {
++str;
++len;
}
return len;
}
6.递归和非递归分别实现求n的阶乘
int FactorialRec(int n) {
if (n < 1) {
return -1;
}
if (n == 1) {
return 1;
}
return n * FactorialRec(n - 1);
}
int FactorialNoRec(int n) {
if (n < 1) {
return -1;
}
int result = 1;
for (int curr = 1; curr <= n; ++curr) {
result *= curr;
}
return result;
}
7.递归方式实现打印一个整数的每一位
void Print(int n) {
if (n < 0) {
return -1;
}
if (n == 0) {
return;
}
Print(n / 10);
printf("%d ", n % 10);
}