核心提示:如果您还不知道什么是回文数请看百度百科:http://baike.baidu.com/view/101387.htm函数格式定义如下:function NumberOfPalindromes(cons...
如果您还不知道什么是回文数请看百度百科:http://baike.baidu.com/view/101387.htm
函数格式定义如下:
function NumberOfPalindromes(const maxNumber : int64) : int64;
以最快的速度从1到maxNumber找出回文数
例如:如果maxNumber是10,那找出的结果应该是18个,分别是:1, 2, 3, 4, 5, 6, 7, 8, 9, 11, 22, 33, 44, 55, 66, 77, 88, 99
本文摘取了一个最佳最快的算法示例:
function CarlosTrevino_NumberOfPalindromes(const maxNumber : int64) : int64;
var
N,j: Int64;
Even: Boolean;
Digits: Array[1..20] of Integer;
K: Integer;
Mid,Top,d: Integer;
L: Integer;
begin
N:=MaxNumber div 10;
result:=0;
j:=9;
Even:=False;
// This part only if functions accept
// numbers that are not multiples of ten
k:=1;
Digits[k]:=MaxNumber mod 10;
while N>0 do
begin
result:=result+j;
if Even then j:=j*10;
Even:=Not Even;
// This part only if functions accept
// numbers that are not multiples of ten
k:=k+1;
// This part only if functions accept
// numbers that are not multiples of ten
Digits[k]:=N mod 10;
N:=N div 10;
end;
// From here, only necesary if function
// accept numbers that are not multiples of ten
Mid:=k div 2;
Top:=k;
j:=1;
for L := 1 to Mid do
begin
if Digits[L]<Digits[top] then D:=Digits[L]
else D:=Digits[Top];
if L>1 then j:=j*(d+1)
else j:=j*d;
Dec(Top) ;
end;
if (k>1) and ((k mod 2)>0) then j:=j*(Digits[Mid+1]+1) ;
result:=result+j;
end;
测试数据:最大范围10 000 000,耗时:1550纳秒,更多其它算法,一共17种打包下载
迅雷专用高速下载