题意: 输入n,打印第n个回文数,n最多10万位。
思路:构造似乎不太可能,因为位数太多了,于是考虑n和回文数之间的联系,即打表找规律。
发现,如果首位不是1,那么回文数首位分别为首位减一,中间的数为n剩下数进行回文操作。
如果首位是1,又分为第二位是0和不是0的情况,是0的话,那么把n除去首位进行回文化即可,否则,所求回文数首尾位为9(也就相当于之前首位为10的情况),其余如旧进行回文化。
#include <bits/stdc++.h>
using namespace std;
const int maxn = 1000000;
string s;
string tmp;
map<string,int > ma;
int main()
{
ma["1"] = 0;
ma["2"] = 1;
ma["3"] = 2;
ma["4"] = 3;
ma["5"] = 4;
ma["6"] = 5;
ma["7"] = 6;
ma["8"] = 7;
ma["9"] = 8;
ma["10"] = 9;
ma["11"] = 11;
ma["12"] = 22;
ma["13"] = 33;
ma["14"] = 44;
ma["15"] = 55;
ma["16"] = 66;
ma["17"] = 77;
ma["18"] = 88;
ma["19"] = 99;
int t;
cin>>t;
while(t--)
{
cin>>s;
int len =s.size();
if(len <= 1)
{
cout<<ma[s]<<endl;
continue;
}
if(len ==2 &&s[0]=='1')
{
cout<<ma[s]<<endl;
continue;
}
if(s[0]!= '1')
{
tmp = s.substr(1,len-1);
cout<<char(s[0]-1);
cout<<tmp;
for(int i = tmp.size()-2; i >= 0; i--)
{
cout<<tmp[i];
}
cout<<char(s[0]-1);
cout<<endl;
}
else
{
if(s[1] != '0')
{
tmp = s.substr(1);
cout<<tmp;
for(int i = tmp.size()-1; i >= 0; i--)
{
cout<<tmp[i];
}
}
else
{
tmp = s.substr(2);
cout<<9;
cout<<tmp;
for(int i = tmp.size()-2; i >= 0; i--)
{
cout<<tmp[i];
}
cout<<9;
}
cout<<endl;
}
}
return 0;
}