1. Computing & Technology

Discuss in my forum

Challenge: Number of Palindromic Numbers

By , About.com Guide

Question: Challenge: Number of Palindromic Numbers
Challenge: provide the implementation of a custom Delphi function to locate all palindromic numbers from 1 to maxNumber and return the number of found palindromes as a result of the function.

The code is submitted for the Number of Palindromic Numbers Delphi Challenge

Answer: Number of palindromic numbers entry by Geoffrey Phillips (USA):
 function GeoffreyPhillips_NumberOfPalindromes(const maxNumber : int64) : int64;
 var
   Pals : int64;
   LLong, LShort, j, LenHalf: integer;
   SMax, STmp, SLeft, SRight, SPalLeft : string[20];
 const
   // int64 shorter than 20 digits
   Ref : array[1..20] of int64 = (10, 19, 109, 199, 1099, 1999, 10999, 19999, 109999, 199999, 1099999, 1999999, 10999999, 19999999, 109999999, 199999999, 1099999999, 1999999999, 10999999999, 19999999999) ;
 begin
   if maxNumber < 10 then
   begin
     result := maxNumber + 1;
     exit;
   end;
 
   SMax := inttostr(maxNumber) ;
 
   LLong := Length(SMax) ;
   LShort := trunc(LLong / 2) ;
 
   if not Odd(LLong) then LenHalf := LShort else LenHalf := LShort + 1;
 
   Pals := Ref[LLong - 1];
 
   STmp := copy(SMax, 1, LenHalf) ;
 
   j := strtoint(STmp[1]) - 1;
   STmp[1] := inttostr(j)[1];
   Pals := Pals + strtoint64(STmp) ;
 
   SLeft := copy(SMax, 1, LenHalf) ;
   SRight := copy(SMax, LShort + 1, LenHalf) ;
   SPalLeft := SLeft;
 
   for j := 1 to Lenhalf do
   begin
     SPalLeft[j] := SLeft[LenHalf + 1 - j];
   end;
 
   if SRight >= SPalLeft then Pals := Pals + 1;
 
   result := Pals;
 end;
 

Test data: MAXNUMBER = 10 000 000

Geoffrey's speed result: 3000 nanoseconds.

Explore the list of all accepted entries for the Number of Palindromic Numbers Delphi Challenge.

Readers Respond: Your Delphi Programming Challenges

©2012 About.com. All rights reserved.

A part of The New York Times Company.