A palindrome is a word, number, or phrase that reads the same forwards as backwards. For example, the name "anna" is a palindrome. Numbers can also be palindromes (e.g. 151 or 753357). Additionally numbers can of course be ordered in size. The first few palindrome numbers are: 1, 2, 3, 4, 5, 6, 7, 8, 9, 11, 22, 33, ...
The number 10 is not a palindrome (even though you could write it as 010) but a zero as leading digit is not allowed.
Input
The input consists of a series of lines with each line containing one integer value i (1 <= i <= 2*109) . This integer value i indicates the index of the palindrome number that is to be written to the output, where index 1 stands for the first palindrome number (1) , index 2 stands for the second palindrome number (2) and so on. The input is terminated by a line containing 0 .Output
For each line of input (except the last one) exactly one line of output containing a single (decimal) integer value is to be produced. For each input value i the i-th palindrome number is to be written to the output.Sample Input
1 12 24 0
Sample Output
1 33 151
题意:
回文数从小到大排列为:1,2,3,4,5,6,7,8,9,11,22,33...。输入n(1<=n<=2*10^9),求第n小的回文数。
很容易可以发现回文数的规则,首先是位数增长,1位2位3位...
对于i位的回文数,首先是第一位由1,2..到9。然后第2位0,1..9
所以得出i位长的回文数有 9 * 10^((i-1)/2) 个
所以可以得出第n小的回文数的长度,然后同理可以得出第一位,然后递归找出第2,3...mid位对应的数字 具体看程序
#include <cstdio>
#include <iostream>
#include <vector>
#include <algorithm>
#include <cstring>
#include <string>
#include <map>
#include <cmath>
#include <queue>
#include <set>
using namespace std;
//#define WIN
#ifdef WIN
typedef __int64 LL;
#define iform "%I64d"
#define oform "%I64d\n"
#define oform1 "%I64d"
#else
typedef long long LL;
#define iform "%lld"
#define oform "%lld\n"
#define oform1 "%lld"
#endif
#define S64I(a) scanf(iform, &(a))
#define P64I(a) printf(oform, (a))
#define P64I1(a) printf(oform1, (a))
#define REP(i, n) for(int (i)=0; (i)<n; (i)++)
#define REP1(i, n) for(int (i)=1; (i)<=(n); (i)++)
#define FOR(i, s, t) for(int (i)=(s); (i)<=(t); (i)++)
const int INF = 0x3f3f3f3f;
const double eps = 10e-9;
const double PI = (4.0*atan(1.0));
const int maxn = 30;
LL p10[maxn];
LL cnt[maxn];
LL sum[maxn];
void init() {
p10[0] = 1;
for(int i=1; i<maxn; i++) p10[i] = p10[i-1] * 10;
sum[0] = 0;
for(int i=1; i<maxn; i++) {
cnt[i] = 9 * p10[(i-1)/2];
sum[i] = sum[i-1] + cnt[i];
}
}
int ans[20];
int len;
void f(int i, int step) {
if(!step) return ;
int j = len - 1 - i;
int p = (j - i - 2) / 2 + 1;
ans[i] = ans[j] = (step-1) / p10[p];
if(p) f(i+1, step-ans[i]*p10[p]);
}
int main() {
int n;
init();
while(scanf("%d", &n) != EOF && n) {
len = 1;
while(sum[len] < n) len++;
if(len == 1) {
printf("%d\n", n);
continue;
}
if(len == 2) {
n -= 9;
printf("%d%d\n", n, n);
continue;
}
n -= sum[len-1];
int p = (len-3) / 2 + 1;
ans[0] = ans[len-1] = (n-1) / p10[p] + 1;
n -= (ans[0] - 1) * p10[p];
if(n) f(1, n);
for(int i=0; i<len; i++) {
printf("%d", ans[i]);
}
putchar('\n');
}
return 0;
}