UVA - 12050 Palindrome Numbers

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

先观察一个n位数可以产生多少个回文数(不包括少于n位的数字),除去对称的一边,其可以任意改变的位数t=n/2+n%2,其中第一位数不能为0,则其能生成9e(t-1)个回文数,那么通过这个规则,使用while循环,就可以得知要输出的回文的位数。

然后就是回文排序的问题,这就是一个简单的数学问题,用题目要求的数据的i减去1到n-1位数能生成的回文数,我们得到余数p,p的意义是在一个t位数上第p小的数字,再以回文的形式输出它的另一半即可。

另外题目中i的最大值位2e9,所以题目中部分数据要用long long。

#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<cmath>
#include<stack>
#include<map>
using namespace std;
const int MAX=1e5+10;
#define INF 0x7fffffff
#define ll long long
#define FOR(i,n) for(i=1;i<=n;i++)
#define mst(a) memset(a,0,sizeof(a))
#define mstn(a,n) memset(a,n,sizeof(a))
//struct num{int a,b,i;}a[1005];
//bool cmp(const num &x, const num &y){return x.a>y.a;}

int main()
{
    int n;    
    while(scanf("%d",&n)&&n)
    {
        ll p=9;
        int t=1,i,s[MAX];
        while(n>p)
        {
            t++;
            n-=p;
            if(t>=3&&t%2==1)
            {
                p*=10;
            }
        }
        int len=t/2+t%2,k=p/9;
        n+=k-1;    
        for(i=len;i>=1;i--)
        {
            s[i]=n%10;
            n/=10;
        }    
        for(i=1;i<=len;i++) cout<<s[i];
        if (t%2) len--;
        for(i=len;i>=1;i--) cout<<s[i];
        cout<<endl;
    } 
    return 0;
}

 

posted @ 2017-07-06 14:10  诚信肥宅  阅读(164)  评论(0编辑  收藏  举报