[英]need algorithm to find the nth palindromic number
consider that 考虑一下
0 -- is the first
1 -- is the second
2 -- is the third
.....
9 -- is the 10th
11 -- is the 11th
what is an efficient algorithm to find the nth palindromic number? 什么是找到第n个回文数的有效算法?
I'm assuming that 0110 is not a palindrome, as it is 110. 我假设0110不是回文,因为它是110。
I could spend a lot of words on describing, but this table should be enough: 我可以花很多时间来描述,但这个表应该足够了:
#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...
The (nonzero) palindromes with even number of digits start at p(11) = 11, p(110) = 1001, p(1100) = 100'001,...
. 具有偶数位数的(非零)回文从
p(11) = 11, p(110) = 1001, p(1100) = 100'001,...
They are constructed by taking the index n - 10^L
, where L=floor(log10(n))
, and append the reversal of this number: p(1101) = 101|101, p(1102) = 102|201, ..., p(1999) = 999|999, etc
. 它们是通过取索引
n - 10^L
构造的,其中L=floor(log10(n))
,并附加该数字的反转: p(1101) = 101|101, p(1102) = 102|201, ..., p(1999) = 999|999, etc
。 This case must be considered for indices n >= 1.1*10^L but n < 2*10^L
. 对于指数
n >= 1.1*10^L but n < 2*10^L
必须考虑这种情况。
When n >= 2*10^L
, we get the palindromes with odd number of digits, which start with p(2) = 1, p(20) = 101, p(200) = 10001 etc.
, and can be constructed the same way, using again n - 10^L with L=floor(log10(n))
, and appending the reversal of that number, now without its last digit : p(21) = 11|1, p(22) = 12|1, ..., p(99) = 89|8, ...
. 当
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, ...
When n < 1.1*10^L
, subtract 1 from L to be in the correct setting with n >= 2*10^L
for the case of an odd number of digits. 当
n < 1.1*10^L
,对于奇数位数的情况,从L减去1到正确的设置,其中n >= 2*10^L
This yields the simple algorithm: 这产生了简单的算法:
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] ))
}
where [...] is 1 if ... is true, 0 else, and \\ is integer division. 其中[...]为1如果...为真,则为0,而\\为整数除法。 (The expression
n \\ 10^[...]
is equivalent to: if ... then n\\10 else n
.) (表达式
n \\ 10^[...]
相当于: if ... then n\\10 else n
。)
(I added the condition n > 1 in the exponent to avoid P = 10^(-1) for n=0. If you use integer types, you don't need this. Another choice it to put max(...,0) as exponent in P, or use if n=1 then return(0)
right at the start. Also notice that you don't need L after assigning P, so you could use the same variable for both.) (我在指数中添加了条件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.