1. 程式人生 > >E - Palindrome Numbers

E - Palindrome Numbers

cep sizeof rod 個人 map ads nes where sample

題目鏈接:https://vjudge.net/contest/237394#problem/E

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 ?rst 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 ?rst 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個回文數,從1開始

個人思路:這題要先找規律,可以發現增長關系是9,9,90,90,900,900····一直下去,這樣就可以把要求的數所在的小範圍區間求出來,求該數是這個範圍內第幾個數,然後求出來就行

看代碼

#include<iostream>
#include<cstdio>
#include<cstring>
#include<stdio.h>
#include<string.h>
#include<cmath>
#include<math.h>
#include<algorithm>
#include
<set> #include<queue> #include<map> typedef long long ll; using namespace std; const ll mod=1e9+7; const int maxn=1e8+10; const int maxk=100+10; const int maxx=1e4+10; const ll maxa=2520; #define INF 0x3f3f3f3f3f3f ll a[50]; ll ans[25]; void solve(ll n,ll W) { int cnt=W; // cout<<n<<" "<<W<<endl;
ans[cnt--]=n%10-1;//最後一位是從0開始的,所以要減1,但是這裏要註意,n%10可能為0,為0的話其實就是上一位減1,這一位加10 n=n/10;//同時n減少一位 if(ans[W]<0) { ans[W]=ans[W]+10; n--; } while(n) { ans[cnt--]=n%10; n/=10; } ans[1]++;//註意第一位從1開始的,要++ } int main() { ios::sync_with_stdio(false); ll sum=1,sum1=0,P; for(int i=1;i<=50;i+=2) { a[i]=a[i+1]=9*sum; sum*=10; sum1+=a[i]*2; if(sum1>=2*pow(10,9)) { P=i; break; } } ll n; a[0]=0; while(cin>>n) { memset(ans,0,sizeof(ans)); sum=0; int W; if(n==0) break; if(n>0&&n<10) { cout<<n<<endl; continue; } for(int i=1;i<=P;i++) { sum+=a[i]; if(n<=sum) { W=i; sum-=a[i]; n-=sum; break; } } //cout<<W<<endl; if(W%2==0) { W=W/2; solve(n,W); for(int i=1;i<=W;i++) cout<<ans[i]; for(int i=W;i>=1;i--) cout<<ans[i]; } else { W=(W+1)/2; solve(n,W); for(int i=1;i<=W;i++) cout<<ans[i]; for(int i=W-1;i>=1;i--) cout<<ans[i]; } cout<<endl; // cout<<n<<endl; //cout<<ans<<endl; } return 0; }

E - Palindrome Numbers