1560: The Least Palindromic Number
Time Limit: 1 Sec Memory Limit: 128 MBSubmit: 111 Solved: 15
[ Submit][ Status][ Web Board]
Description
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.
Input
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.
Output
For each the case, your program will output the least palindromic number P (P > N) on separate line.
Sample Input
Sample Output
#include <stdio.h>
#include <string.h>
char num[10005], left[10005], right[10005];
void reverse( char *left, char *right, char center, int info )
{
int len= strlen( left );
for( int i= len- 1, j= 0; i>= 0; --i, ++j )
{
right[j]= left[i];
}
if( info )
{
left[len]= center, left[ len+ 1 ]= '\0';
}
strcat( left, right );
}
int main()
{
while( scanf( "%s", num )!= EOF )
{
int len= strlen( num ), cnt= 0;
for( int i= 0; i< len; ++i )
{
if( num[i]== '9' )
{
cnt++;
}
}
if( cnt== len )
{
memset( num, '0', sizeof( num ) );
num[0]= num[len]= '1';
num[len+ 1]= '\0';
puts( num );
continue;
}
if( len== 1 )
{
if( num[0]< '9' )
{
printf( "%c\n", num[0]+ 1 );
continue;
}
else
{
puts( "11" );
continue;
}
} // 以上为各种特殊处理
int pos= len/ 2, flag= 0, kind;
char center= num[pos];
num[pos]= '\0';
strcpy( left, num );
if( len& 1 )
{
kind= 1;
strcpy( right, num+ pos+ 1 );
}
else
{
kind= 0;
num[pos]= center;
strcpy( right, num+ pos );
}
for( int i= pos- 1, j= 0; i>= 0; --i, ++j )
{
if( left[i]== right[j] )
{
if( i!= 0 )
{
continue;
}
}
else if( left[i]> right[j] )
{
flag= 1;
reverse( left, right, center, kind );
break;
}
if( left[i]< right[j]|| i== 0 )
{
if( center!= '9'&& len& 1 )
{
center+= 1;
reverse( left, right, center, kind );
flag= 1;
break;
}
else
{
center= '0';
int i= pos- 1;
left[i]+= 1;
while( left[i]> '9' )
{
left[i]= '0';
left[i- 1]+= 1;
--i;
}
reverse( left, right, center, kind );
flag= 1;
break;
}
}
}
if( flag )
{
puts( left );
}
}
}