UVALive 2889

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). Additionallynumbers 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 leadingdigit is not allowed.


題意:讓你求第N個迴文數字。


思路:可以算出來第N個迴文數字,長度多長而且是該長度第幾個迴文串。因爲1位數有9個,2位數9個,3位數90,4位數90,可以預處理出來。


當我們知道長度的時候,也知道是第幾個的時候,直接將第幾個-1然後加上一半長度的迴文數字。

比如:24 可以求出他的迴文長度是3,是第6個。

迴文長度爲3,他的第一個數101,他的左半部分是10

6-1=5; 用5直接加上他的左半部分就可以了。15

那麼將15反着輸出,並且他的長度爲3.所以只輸出1.

則就是151;


#include<stdio.h>
#include<string.h>
const int N=1<<29;
const long long maxn=2e11;
long long num[10000];
int cnt=0;
int a[100],b[100],kb;
void init()
{
    long long t=90;
    num[1]=9,num[2]=18;
    cnt=2;
    for(int i=3;; i+=2)
    {
        num[i]+=num[i-1]+t;
        num[i+1]+=num[i]+t;
        t*=10;
        cnt+=2;
        if(t>maxn)break;
    }
}
long long get(int x)
{
    long long t=9;
    x--;
    while(x--)
    {
        t*=10;
    }
    return t;
}
int chuli(int len,long long cc)
{
    cc--;
    int f=0;
    if(len%2==0)f=1;
    len=(len+1)/2;
    memset(b,0,sizeof(b));
    kb=1;
    //printf("%lld\n",cc);
    while(cc>0)
    {
        int kk=cc%10;
        cc/=10;
        b[kb++]=kk;
    }
    b[len]+=1;

    if(f==0)
    {
        for(int i=len;i>1;i--)
            printf("%d",b[i]);
    }
    else
    {
         for(int i=len;i>=1;i--)
            printf("%d",b[i]);
    }
    for(int i=1; i<=len; i++)
        printf("%d",b[i]);
    puts("");
}
int main()
{
    init();
    int n;
    while(scanf("%d",&n)!=EOF)
    {
        if(!n)break;
        if(n<=9)
        {
            printf("%d\n",n);
            continue;
        }
        int t=1;
        for(int i=1; i<=cnt; i++)
            if(n<=num[i])
            {
                t=i;
                break;
            }
        long long cc=n-num[t-1];
        //printf("%d %d\n",t,cc);
        chuli(t,cc);
    }
    return 0;
}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章