practice_替换空格、斐波那契数列、跳台阶、变态跳台阶

 

实现一个函数,将一个字符串中的空格替换成“%20”。

eg:We Are Happy.替换之后的字符串为We%20Are%20Happy.

 

#include<stdio.h>
#include<string.h>
#include<windows.h>

/*
替换空格:
实现一个函数,将一个字符串中的空格替换成“%20”
例如,当字符串为We Are Happy.
则经过替换之后的字符串为We%20Are%20Happy。
*/

char *replaceSpace(char *str, int length) {
	char *res = str;
	char *replace = "%20";
	int len = strlen(replace);
	int count = 0;
	while (*str){
		count++;
		if (*str == ' '){
			memmove(str + 2, str, length - count + 2);//将默认的'\0'也后移过去
			char *re1 = replace;
			while (*re1){
				*str = *re1;
				re1++;
				str++;
			}
		}
		else{
			str++;
		}
	}
	return res;
}

int main()
{
	char str[] = "We Are Happy.";
	printf("%s\n", replaceSpace(str, strlen(str)));
	system("pause");
	return 0;
}

运行结果:

迭代求斐波那契数列:特别注意:当n==0时,结果为0。

#include<stdio.h>
#include<string.h>
#include<windows.h>

/*
斐波那契数列
特别注意:当n==0时,结果为0。
*/
int Fibonacci(int n) {
	int first = 1;
	int second = 1;
	int sum = 0;
	if (!n){
		return 0;
	}
	else if (n <= 2){
		return 1;
	}
	else{
		while (n > 2){
			sum = first + second;
			first = second;
			second = sum;
			n--;
		}
	}
	return sum;
}

int main()
{
	printf("%d\n", Fibonacci(1));
	system("pause");
	return 0;
}

 

跳台阶:一只青蛙一次可以跳上1级台阶,也可以跳上2级。求该青蛙跳上一个n级的台阶总共有多少种跳法。

#include<stdio.h>
#include<math.h>
#include<string.h>
#include<windows.h>

/*
跳台阶:
一只青蛙一次可以跳上1级台阶,也可以跳上2级。
求该青蛙跳上一个n级的台阶总共有多少种跳法。
*/
/*
0 0
1 1(1)
2 2(2/1)
3 3(1 1 1/2 1/1 2)
4 5(1 1 1 1/1 1 2/1 2 1/2 1 1/2 2)
5 8(1 1 1 1 1/1 1 1 2/1 1 2 1/1 2 1 1/2 1 1 1/2 2 1/1 2 2/2 1 2)
*/
int jumpFloor(int number) 
{//找出其中规律:当前台阶次数等于前两数之和
	if (number == 0){
		return 0;
	}
	if (number == 1){
		return 1;
	}
	if (number == 2){
		return 2;
	}
	int one = 1;
	int two = 2;
	int res = 0;
	while (number > 2){
		res = one + two;
		one = two;
		two = res;
		number--;
	}
	return res;
}

int main()
{
	printf("%d\n", jumpFloor(1));

	system("pause");
	return 0;
}

 

变态跳台阶:一只青蛙一次可以跳上1级台阶,也可以跳上2级……它也可以跳上n级。求该青蛙跳上一个n级的台阶总共有多少种跳法。

 

#include<stdio.h>
#include<math.h>
#include<string.h>
#include<windows.h>

/*
变态跳台阶:
一只青蛙一次可以跳上1级台阶,
也可以跳上2级……它也可以跳上n级。
求该青蛙跳上一个n级的台阶总共有多少种跳法。
*/
/*
0 0
1 1
2 2
3 4(1 1 1/1 2/2 1/3)
4 8(1 1 1 1/1 1 2/1 2 1/2 1 1/2 2/1 3/3 1/4)
5 16(1 1 1 1 1/1 1 1 2/1 1 2 1/1 2 1 1/2 1 1 1/2 2 1/1 2 2/2 1 2/3 1 1/1 3 1/1 1 3/3 2/2 3/4 1/1 4/5)
*/
int jumpFloorII(int number) 
{//找出规律:当前台阶次数是2 的(台阶数-1)次方
	if (number == 0){
		return 0;
	}
	return pow(2, number - 1);
}

int main()
{
	printf("%d\n", jumpFloorII(5));

	system("pause");
	return 0;
}

 

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值