12050 - Palindrome Numbers
Time limit: 3.000 seconds
http://uva.onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&category=467&page=show_problem&problem=3202
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*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 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
打表,先根據表找出這個回文數有多少位,然後算一般,另一半照前面的輸出。
完整代碼:
/*0.015s*/
#include<cstdio>
#include<cstring>
#include<cstdlib>
const int endsum[21] =
{
0, 9, 18, 108, 198, 1098, 1998, 10998, 19998, 109998, 199998, 1099998, 1999998,
10999998, 19999998, 109999998, 199999998, 1099999998, 1999999998, 2000000001
};
char str[20];
int main(void)
{
int len, num, i, j, maxj;
int ans;
while (gets(str), str[0] & 15)
{
len = strlen(str);
num = atoi(str);
if (len == 1)
putchar(str[0]);
else if (num < 19)
{
num += 39;
putchar(num);putchar(num);
}
else
{
i = 2;
while (endsum[++i] < num)
;
/// 此時回文數的位數為i
num -= endsum[i - 1] + 1; /// 多減一個
/// 現在num是第num個i位數的回文數
ans = 1;
maxj = (i + 1) >> 1; /// i/2上取整
for (j = 1; j < maxj; ++j)
ans *= 10;
ans += num;
sprintf(str, "%d", ans);
for (j = 0; j < maxj; ++j)
putchar(str[j]);
if ((i & 1) == 0)///優先級啊。。
putchar(str[maxj - 1]);
for (j = maxj - 2; j >= 0; --j)
putchar(str[j]);
}
putchar('\n');
}
return 0;
}