您的位置:首页 > 其它

POJ - 2042 - Palindrome Numbers

2017-08-06 09:40 369 查看
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 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*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个回文串数字(1,2,3,4,5,6,7,8,9,11,22,33,44,55,66,...),其中不存在有前导零的数

n位数和 n+1(n为奇数) / n-1(n为偶数)位数所含有的回文串数字个数相同,均为(10^(n/2+n%2-1))*9,因为除最外层只有1-9九种选择,其他位都是有0-9十种选择。

所以我们可以先确定位数,再确定各个位置上的数字。

因为是对称的,所以我们只用求一半的数字就行了,设一半的位数位haf,第 i 位上的数字 +1 就是遍历过了10^(i-1)种数字,因为是按从小到大的顺序来的,所以先变的是中间的数,然后再往两边推,所以我们就反过来遍历就行了。

#include<iostream>
#include<stdio.h>
#include<math.h>
#include<string.h>
using namespace std;
#define LL long long
LL n,a[15];
int main()
{
a[0] = 1;
for(int i=1; i<=10; i++)
a[i] = pow(10,i-1)*9;
while(cin>>n,n)
{
int i;
for(i=1;;i++)
{
if(n-a[i/2+i%2]<=0)
break;
n-=a[i/2+i%2];
}
int haf = i/2+i%2,num[1111];//我取的是后半部分
int p = i%2;
memset(num,0,sizeof num);
num[haf] = 1;//最后一位只能从1开始
n--;
while(n)
{
for(int i=haf; i>=1; i--)
{
if(n>=pow(10,i-1))
num[i]+=n/pow(10,i-1);
n%=(LL)pow(10,i-1);
}
}
for(int i=haf; i>=1; i--)
cout<<num[i];
for(int i=1+p;i<=haf;i++)
cout<<num[i];
cout<<endl;
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: