蓝桥杯 算法训练 回文数

算法训练 回文数  
时间限制:1.0s   内存限制:256.0MB
   
问题描述
  若一个数(首位不为零)从左向右读与从右向左读都一样,我们就将其称之为回文数。
  例如:给定一个10进制数56,将56加65(即把56从右向左读),得到121是一个回文数。

  又如:对于10进制数87:
  STEP1:87+78 = 165 STEP2:165+561 = 726
  STEP3:726+627 = 1353 STEP4:1353+3531 = 4884

  在这里的一步是指进行了一次N进制的加法,上例最少用了4步得到回文数4884。

  写一个程序,给定一个N(2<=N<=10或N=16)进制数M(其中16进制数字为0-9与A-F),求最少经过几步可以得到回文数。
  如果在30步以内(包含30步)不可能得到回文数,则输出“Impossible!”
输入格式
  两行,N与M
输出格式
  如果能在30步以内得到回文数,输出“STEP=xx”(不含引号),其中xx是步数;否则输出一行”Impossible!”(不含引号)
样例输入
9
87
样例输出
STEP=6
代码如下:
 
 
#include<iostream>
#include<string>
#include<vector>
#include<cctype>
using namespace std;
bool Huiwen(string s)
{
	int i = 0, j = s.length() - 1;
	while (i < j)
	{
		if (s[i] == s[j])
		{
			i++; j--;
		}
		else
			return false;
	}
	return true;
}
void Judge(int n, string m, int k)
{
	if (k > 30)
	{
		cout << "Impossible!" << endl;
		return;
	}
	if (Huiwen(m))
		cout << "STEP=" << k << endl;
	else
	{
		string s;
		int i = 0, j = m.length() - 1, t = 0;
		while (i <m.length())
		{
			int a, b;
			if (isupper(m[i]))
				a = (m[i] - 'A') + 10;
			else
				a = (m[i] - '0');

			if (isupper(m[j]))
				b = (m[j] - 'A') + 10;
			else
				b = (m[j] - '0');

			char c;
			if ((a + b + t) % n < 10)
				c = (a + b + t) % n + '0';
			else
				c = (a + b + t) % n - 10 + 'A';

			s = c + s;
			t = (a + b + t) / n;
			i++;
			j--;
		}

		char c = t + '0';
		if (t)s = c + s;
		Judge(n, s, k + 1);
	}
}
int main()
{
	int n;
	string m;
	cin >> n >> m;
	Judge(n, m, 0);
	return 0;
}

这个题就是用递归一步一步算出来,难点在于16进制的转化,要写一些判断,还有k超过30就结束运行,不然会超时

猜你喜欢

转载自blog.csdn.net/tobealistenner/article/details/80080291