递归——牛客一星OJ整理

目录

1.字符串逆序

2.The best water problem

题目描述

输入描述:

输出描述:

输入

输出

说明

输入

输出

说明

3.pocky

题目描述

输入描述:

输出描述:

输入

输出


1.字符串逆序

我觉得不用递归,送分题……

题目描述


输入一个字符串,长度在100以内,按相反次序输出其中的所有字符。
输入描述:

输入一个字符串

输出描述:

输出反序的字符串

示例1
输入
复制

tsinghua

输出
复制

auhgnist

备注:

送分题 送分题

#include <iostream>
using namespace std;

int main(){
	
	char s[101];
	char ch;
	int i=0;
	while(ch=cin.get()){//注意这里处理方法!写成cin>>ch就是不行,不知道为啥。。。 
		if(ch=='\n'){
			break;
		}else{
			s[i++]=ch;
		}
	}
	for(int j=i-1;j>=0;j--){
		cout<<s[j];
	}
	cout<<endl;
	
	return 0;
} 

2.The best water problem

链接:https://ac.nowcoder.com/acm/problem/15173
来源:牛客网
 

题目描述

给你一个数,让他进行巴啦啦能量,沙鲁沙鲁,小魔仙大变身,如果进行变身的数不满足条件的话,就继续让他变身。。。直到满足条件为止。

巴啦啦能量,沙鲁沙鲁,小魔仙大变身:对于一个数,把他所有位上的数字进行加和,得到新的数。

如果这个数字是个位数的话,那么他就满足条件。

输入描述:

给一个整数数字n(1<=n<=1e9)。

输出描述:

输出由n经过操作满足条件的数

示例1

输入

复制

12

输出

复制

3

说明

12 -> 1 + 2 = 3

示例2

输入

复制

38

输出

复制

2

说明

38 -> 3 + 8 = 11 -> 1 + 1 = 2

 不用递归:(其实他的测试样例没考虑比较大数的情况,我这都能AC……)

#include <iostream>
using namespace std;

int num=0;

int main(){
	
	string s;
	cin>>s;
	for(int i=0;i<s.length();i++){
		num+=s[i]-'0';
	}
	while(num>=10){
		int a=num/10;
		int b=num%10;
		num=a+b;
	}
	cout<<num<<endl;
	
	return 0;
}

用递归:

#include <iostream>
using namespace std;

int digui(int num){
	int sum=0;
	while(num>0){
		sum+=num%10;
		num=num/10;
	}
	if(sum<10&&sum>=0){
		return sum;
	}else{
		return digui(sum);//不加上return就会炸…… 
	}
	
}

int main(){
	
	int num;
	cin>>num;
	
	int sum=digui(num);
	
	cout<<sum<<endl;
	
	return 0;
}

3.pocky

链接:https://ac.nowcoder.com/acm/problem/19012
来源:牛客网
 

题目描述

Let’s talking about something of eating a pocky. Here is a Decorer Pocky, with colorful decorative stripes in the coating, of length L. 

While the length of remaining pocky is longer than d, we perform the following procedure. We break the pocky at any point on it in an equal possibility and this will divide the remaining pocky into two parts. Take the left part and eat it. When it is not longer than d, we do not repeat this procedure. 

Now we want to know the expected number of times we should repeat the procedure above. Round it to 6 decimal places behind the decimal point. 

输入描述:

The first line of input contains an integer N which is the number of test cases. Each of the N lines contains two float-numbers L and d respectively with at most 5 decimal places behind the decimal point where 1 ≤ d,L ≤ 150.

输出描述:

For each test case, output the expected number of times rounded to 6 decimal places behind the decimal point in a line.

示例1

输入

复制

6 
1.0 1.0
2.0 1.0
4.0 1.0
8.0 1.0
16.0 1.0
7.00 3.00

输出

复制

0.000000
1.693147
2.386294
3.079442
3.772589
1.847298

题目没看懂,先放这

发布了228 篇原创文章 · 获赞 76 · 访问量 6万+

猜你喜欢

转载自blog.csdn.net/qq_41895747/article/details/103882753