计蒜课 回文数

一个正整数,如果交换高低位以后和原数相等,那么称这个数为回文数。

比如 121 121 2332 2332 都是回文数, 13 13 4567 4567 不是回文数。

任意一个正整数,如果其不是回文数,将该数交换高低位以后和原数相加得到一个新的数,如果新数不是回文数,重复这个变换,直到得到一个回文数为止。

例如, 57 57 变换后得到 132 ( 57 + 75 ) 132(57 + 75) 132 132 得到 363 ( 132 + 231 ) 363(132 + 231) 363 363 是一个回文数。

曾经有数学家猜想:对于任意正整数,经过有限次上述变换以后,一定能得出一个回文数。

至今这个猜想还没有被证明是对的。

现在请你通过程序来验证。

输入格式

输入一行一个正整数 n n

输出格式

输出第一行一个正整数,表示得到一个回文数的最少变换次数。

接下来一行,输出变换过程,相邻的数之间用"—>"连接。

输出格式可以参见样例。

保证最后生成的数在 int 范围内。

样例输入

349

样例输出

3

349—>1292—>4213—>7337

#include <iostream>
#include<algorithm>
#include<queue>
#include<string>
using namespace std;
bool Judge(int n)  //判断是不是回文数
{
	string str=to_string(n);
	string str2=str;
	int length=str.length();
	reverse(str2.begin(),str2.begin()+length); //将str2逆序
	if(str==str2)
	{
		return true;
	}
	else
	{
		return false;
	}
}
int main() {
	int n;
	cin>>n;
	queue<int> q; //用队列保存n值
	q.push(n);
	int sum=0;
	while(Judge(n)==0)
	{
		int m=0;
		int t=n;
		while(t)
		{
			m=m*10+t%10;  //将n值逆序
			t=t/10;
		}
		n=m+n;
		q.push(n);
		sum++;
	}
	cout<<sum<<endl;
	cout<<q.front();  //输出头元素
	q.pop();
	while(!q.empty())
	{
		cout<<"--->";
		cout<<q.front();
		q.pop();
	}
	return 0;
}

猜你喜欢

转载自blog.csdn.net/wait_13/article/details/86498576
今日推荐