Palindrome Numbers
Palindrome Numbers
Time Limit: 1000MS Memory Limit: 65536K
Total Submissions: 3948 Accepted: 1505
Description
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 010 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*10^9 ). 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
Source
Tehran 2003 Preliminary
題意:
輸入N求第N個迴文數字。
思路:
先求出要求的數位數,然後對半分,直接求一半的數,後一半根據左邊可以求得。
#include<iostream>
#include<cstdio>
#include<algorithm>
#include<cstring>
#include<cmath>
#include<set>
#include<queue>
#include<stack>
using namespace std;
typedef long long ll;
const int mod = 1e9+7;
const double PI = 4*atan(1.0);
const int INF = 0x3f3f3f3f;
const ll LINF = 1ll<<62;
#define maxn 20
ll cnt[20];
void pro()//根據規律預處理。
{
cnt[1]=9;
for(int i=2; i<=20; i++)
{
if(i%2!=0)
cnt[i]=cnt[i-1]*10;
else
cnt[i]=cnt[i-1];
}
}
int main()
{
pro();
ll n;
while(cin>>n&&n)
{
int i=1;
while(n>0)
{
n=n-cnt[i];
i++;
}
i--;//要求的數的位數
// cout<<i<<endl;
n=n+cnt[i];
ll left=1;
for(ll j=1; j<(i+1)/2; j++)
left*=10;
ll res=left+n-1;
left=res;
// cout<<left<<endl;
// cout<<res<<endl;
if(i%2==1)
{
left=left/10;
}//如果位數是奇數,最後一位就是左邊中間的,右邊數字直接舍掉。
while(left)
{
ll right=left%10;
res=res*10+right;//相當於取和左邊對稱的數
left/=10;
}
cout<<res<<endl;
}
return 0;
}