递归训练:到底有多二(简单递归)

L1-017 到底有多二 (15 分)
一个整数“犯二的程度”定义为该数字中包含2的个数与其位数的比值。如果这个数是负数,则程度增加0.5倍;如果还是个偶数,则再增加1倍。例如数字-13142223336是个11位数,其中有3个2,并且是负数,也是偶数,则它的犯二程度计算为:3/11×1.5×2×100%,约为81.82%。本题就请你计算一个给定整数到底有多二。

输入格式:

输入第一行给出一个不超过50位的整数N。

输出格式:

在一行中输出N犯二的程度,保留小数点后两位。

输入样例:

-13142223336
输出样例:

81.82%

【思路】
思路上没什么难的,设函数f(n)表示字符串前n位中字符2的个数。
递推式:f(n) = f(n - 1) + a[n] == ‘2’ ? 1 : 0;
然后就是一些细节处理了

AC代码:

#include<iostream>
using namespace std;

bool fu = false;			//标记是否为负数 
string s;
double res = 1;

int f(int n)				//计算 字符串中2的个数 
{
	//边界 
	if(n == 0)
	{
		if(s[n] == '-')
		{
			res *= 1.5;
			fu = true;
			return 0;
		}
		else if(s[n] == '2')
		{
			return 1;
		}
		else
		{
			return 0;
		}
	}
	
	if(s[n] == '2')
		return f(n - 1) + 1;
	else
		return f(n - 1);
}

int main()
{
	cin >> s;
	int len = s.size();
	if((s[len - 1] - '0') % 2 == 0)
	{
		res *= 2.0;
	}
	int num = f(len - 1);			//记录2的个数
	double x;
	if(fu)
	{
		x = (double)num / ((double)len - 1.0);		//把负号减掉 
	}
	else
	{
		x = (double)num / (double)len;
	}
	x *= res;
	x *= 100;
	printf("%.2f%%\n", x);
	return 0;
}

猜你喜欢

转载自blog.csdn.net/weixin_40163242/article/details/88079281
今日推荐