繁体   English   中英

需要算法来找到第n个回文数

[英]need algorithm to find the nth palindromic number

考虑一下

    0 -- is the first
    1 -- is the second
    2 -- is the third
    .....
    9 -- is the 10th
    11 -- is the 11th

什么是找到第n个回文数的有效算法?

我假设0110不是回文,因为它是110。

我可以花很多时间来描述,但这个表应该足够了:

#Digits #Pal. Notes
   0     1     "0" only
   1     9     x     with x = 1..9
   2     9     xx    with x = 1..9
   3    90     xyx   with xy = 10..99 (in other words: x = 1..9, y = 0..9)
   4    90     xyyx  with xy = 10..99
   5   900     xyzyx with xyz = 100..999
   6   900     and so on...

具有偶数位数的(非零)回文从p(11) = 11, p(110) = 1001, p(1100) = 100'001,... 它们是通过取索引n - 10^L构造的,其中L=floor(log10(n)) ,并附加该数字的反转: p(1101) = 101|101, p(1102) = 102|201, ..., p(1999) = 999|999, etc 对于指数n >= 1.1*10^L but n < 2*10^L必须考虑这种情况。

n >= 2*10^L ,我们得到奇数位数的回文,以p(2) = 1, p(20) = 101, p(200) = 10001 etc. ,并且可以构造以同样的方式,再次使用n - 10^L with L=floor(log10(n)) ,并附加该数字的反转, 现在没有它的最后一位p(21) = 11|1, p(22) = 12|1, ..., p(99) = 89|8, ...

n < 1.1*10^L ,对于奇数位数的情况,从L减去1到正确的设置,其中n >= 2*10^L

这产生了简单的算法:

p(n) = { L = logint(n,10);
         P = 10^(L - [1 < n < 1.1*10^L]); /* avoid exponent -1 for n=1 */
         n -= P; 
         RETURN( n * 10^L + reverse( n \ 10^[n >= P] ))
       }

其中[...]为1如果...为真,则为0,而\\为整数除法。 (表达式n \\ 10^[...]相当于: if ... then n\\10 else n 。)

(我在指数中添加了条件n> 1,以避免在n = 0时P = 10 ^( - 1)。如果使用整数类型,则不需要这个。另外选择它放置max(..., 0)作为P中的指数,或者if n=1 then return(0)使用if n=1 then return(0)在开始时if n=1 then return(0) 。同时注意在分配P后你不需要L,所以你可以对两者使用相同的变量。)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM