[英]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.