A positive integer is called a palindrome if its representation in the
decimal system is the same when read from left to right and from right
to left. For a given positive integer K of not more than 1000000
digits, write the value of the smallest palindrome larger than K to
output. Numbers are always displayed without leading zeros. Input The
first line contains integer t, the number of test cases. Followed by t
lines containing integers K. Output For each K, output the smallest
palindrome larger than K. Example Input:2
808
2133 Output:
818
2222
模拟,情况要考虑周到。
999 192 9999 …
这些容易错的情况注意下应该没什么问题。
CODE:
#include<bits/stdc++.h>
using namespace std;
typedef long long LL;
const int INF = 0x3f3f3f3f;
const double PI=acos(-1);
const int N=1e4;
int t,fla,ffla;
// ffla字符串中间的数是否为9,并且将奇数长度的字符串和偶数长度的字符串分开考虑
// fla 记录在改变除中间两个数之外的其他数时,整个字符串的大小是变大还是变小,还是没有变。
int main()
{
string str;
cin>>t;
while(t--){
fla=-1;ffla=0;
cin>>str;
int len = str.length();
int N=len/2;
if(len%2==0) N--;
for(int i=0;i<N;i++){
if(str[i]!=str[len-1-i]){
if(str[len-1-i]>str[i])
fla=0;
else fla=1;
str[len-1-i]=str[i];
}
}
if(len%2==1){
if(fla==-1||fla==0)
str[len/2]++;
if(str[len/2]>'9')
ffla=1;
}
else{
if(str[len/2-1]==str[len/2])
{
if(fla==-1||fla==0)
str[len/2-1]=str[len/2]=str[len/2-1]+1;
}
else if(str[len/2-1]<str[len/2]){
str[len/2-1]=str[len/2]=str[len/2-1]+1;
}
else{
str[len/2]=str[len/2-1];
}
if(str[len/2]>'9')
ffla=-1;
}
//
if(ffla==1)
{
str[len/2]='0';
int yu=1;
for(int i=len/2-1;i>=0;i--){
str[i]=str[i]+yu;
if(str[i]>'9')
str[i]='0';
else {
yu=0;
break;
}
}
if(yu){
str[0]='0';
str.insert(0,1,'1');
}
int nowlen=str.length();
for(int i=0;i<nowlen/2;i++){
str[nowlen-1-i]=str[i];
}
}
else if(ffla==-1)
{
str[len/2-1]=str[len/2]='0';
int yu = 1;
for(int i=len/2-2;i>=0;i--){
str[i]+=1;
if(str[i]>'9')
str[i]='0';
else{
yu=0;
break;
}
}
if(yu){
str[0]='0';
str.insert(0,1,'1');
}
int nowlen=str.length();
for(int i=0;i<nowlen/2;i++){
str[nowlen-1-i]=str[i];
}
}
cout<<str<<endl;
}
return 0;
}