Palindrome Numbers
Time Limit: 1000MS | Memory Limit: 65536K | |
Total Submissions: 3568 | Accepted: 1333 |
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.
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
题意:
求出第i个回文数
代码:
#include<iostream>
#include<string>
#include<cmath>
using namespace std;
long long num[20]={0, 9, 9, 90, 90, 900, 900, 9000, 9000, 90000, 90000, 900000, 900000, 9000000, 9000000, 90000000,
90000000, 900000000, 900000000, 9000000000};
//num[i]存储i位数的回文数个数
int main()
{
long long n;
int sum;
while(cin>>n!=NULL && n)
{
int i;
sum=0;
for(i=1;i<=19;i++)
{
if(sum+num[i]>=n)
break;
sum+=num[i];
}
n=n-sum-1;
string str(i,'0'); //i为所求答案的位数
str[0]=str[i-1]='1'; //现将所求答案首,末位设为一
if(i==1)
str[0]+=n;
else
{
int j=0;
int s=(int)pow(10.0,(i-2)/2+(i-2)%2); //s控制了下面for循环的次数 与所求答案的位数(i)相关
//i==2:s=1; i==3||i==4:s=10; i==5||i==6:s=100;......
for(;s>=1;s/=10,j++)
{
str[j]+=n/s; //不能为=n/s,因为首末尾设为1
//有外向内改变数字
str[i-j-1]=str[j];
n%=s;
}
}
cout<<str<<endl;
}
return 0;
}