需要算法来找到第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
时,在奇数位数的情况下,用n >= 2*10^L
从L中减去1以达到正确设置。
这就产生了一个简单的算法:
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如果。。。为true,否则为0,\为整数除法。(表达式n 10^[...]
等效于:if ... then n10 else n
。)
(我在指数中添加了条件n>1,以避免n=0时p=10^(-1)。如果您使用整数类型,则不需要它。另一种选择是将max(…,0)作为P中的指数,或者在开始时使用if n=1 then return(0)
。还要注意,在分配P之后不需要L,所以可以对两者使用相同的变量。)
- C++:正在检查LinkedList中的回文-递归方法-错误
- Usaco第1.6节主要回文
- 最大的回文产品 - 程序未运行,编写解决方案但无法理解问题
- 将 S1 转换为回文,并将 S2 作为其子字符串
- 数回文词
- 最长的回文子串(C++帮助)
- 有人可以详细解释这个回文代码是如何工作的吗?
- 回文递归版本
- 如何检查C ++ STL列表是否为回文?
- 回文数在 1 到 10000 之间
- C++ - 检查结构数据类型中的单词是否为回文
- 是回文作业练习
- 回文递归不停止
- 整数数组中最长的回文
- 回文测试
- 最大的回文产品(Project Euler)——C++
- C++ 回文程序总是给出 0(假)作为输出问题;我的代码哪里有问题?
- C++ 回文算法 - 无法与'operator<'匹配
- 回文分区的这种算法的时间复杂度是多少?
- 需要算法来找到第n个回文数