UVa12050

12050 Palindrome Numbers
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

题意:

       将回文数从小到大依次排列,输入一个正整数n,需要输出第n小的回文数。

分析:

       开一个数组存储长度为i的回文数一共有几个,这样就可以根据输入的n先确定要输出的回文数的长度len,并确定第n小的回文数是长度为len的回文数中的第几个,然后依次求出每一位的数即可得到最终的答案。

 1 #include <cstdio>
 2 #define MAX_BIT 20
 3 // ans数组记录答案,下标从1开始
 4 int bit_num[MAX_BIT + 2],n,ans[MAX_BIT + 2];
 5 void set_bitnum(){
 6     bit_num[0] = 0;
 7     bit_num[1] = bit_num[2] = 9;
 8     for(int i = 3 ; i <= MAX_BIT ; i += 2)
 9         bit_num[i] = bit_num[i + 1] = 10 * bit_num[i - 1];
10 }
11 int calc_bit(int& n){
12     int bitnum = 0;
13     while(n > bit_num[bitnum])
14         n -= bit_num[bitnum],bitnum++;
15     return bitnum;
16 }
17 int main(){
18     set_bitnum();
19     while(scanf("%d",&n) == 1 && n){
20         int len = calc_bit(n);
21         //printf("len: %d\n",len);
22         int index = len / 2 + 1;
23         n = n - 1; // 需要从零开始排列
24         while(n)
25             ans[index++] = n % 10,n /= 10;
26         for(int i = index ; i <= len ; i++)
27             ans[i] = 0;
28         ans[len] += 1;
29         for(int i = 1 ; i <= len / 2 ; i++)
30             ans[i] = ans[len - i + 1];
31         for(int i = 1 ; i <= len ; i++)
32             printf("%d",ans[i]);
33         puts("");
34     }
35     return 0;
36 }
View Code

 

转载于:https://www.cnblogs.com/cyb123456/p/5883649.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值