题目描述
Palindromic numbers are digital strings that read the same both forwards and backwards. For example, 121, 44 and 3 are Palindromic numbers, 175, 36 are not;
For a given integer N, you are to find a palindromic number P that satisfy P>N. However, there are many such palindromic numbers. Your task is to find the least one.
输入
There are several test cases, each test case contains only one positive integer N in one line. The number of digits of N is not exceeding 10,000, and N has not lead zeroes.
The input will finish with the end of file.
输出
For each the case, your program will output the least palindromic number P (P > N) on separate line.
样例输入
44
3
175
样例输出
55
4
181
来源
2011ACM/ICPC 第五届华中南赛区邀请赛
题解
思路
题意要求,数N可达10000位,只能用字符串数组存储,对于回文数,只要求前半部分就可写出后半部分,大致分两种情况,一种是前半部分小于后半部分,前半部分有要+1的,这时候就要判断是否有9,有9存在要增加一位的情况,如999/199/191。另一种简单,因为前半部分大于后半部分,所以,只要把前半部分替换后半部分即可,如321/291.
测试数据
89999
1231
12351
9998
9898
2993
1000
100
192
291
121
99
999
2
10
1991
19991
19191
代码如下
#include <cstdio>
#include <cstring>
#define N 10001
char s[N];
using namespace std;
int main(){
while ( ~scanf("%s",s)){
int len=strlen(s);
int flag=0,i;
for(i=len/2-1;i>=0;--i){
if(s[i]>s[len-1-i]){flag=1;break;}
else if(s[i]<s[len-1-i]){ flag=-1;break;}
}
if(flag!=1){//前半串要加1
//s[(len-1)/2]++;
for(i=(len-1)/2;i>=0;--i){//199 191 999
s[i]++;
if(s[i]>'9'){
s[i]='0';
}else break;
}
if(s[0]=='0'){//999 9999
s[0]='1';
len++;
s[len/2]='0';
}
}
for(i=0;i<len/2;++i)
printf("%c",s[i]);
for(i=(len+1)/2-1;i>=0;--i)
printf("%c",s[i]);
printf("\n");
}
return 0;
}