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 Boris Novgorodov (Russia):
 function BorisNovgorodov_NumberOfPalindromes(const MaxNumber: Int64): Int64;
 const
   TenPowers: array[0..9] of Int64 =
   (1, 10, 100, 1000, 10000, 100000, 1000000, 10000000, 100000000, 1000000000) ;
 
   function PalBeforeTenPower(Pow: Integer): Int64;
   begin
     if Pow = 0 then
       Result := 1
     else if Odd(Pow) then
       Result := 11 * TenPowers[Pow div 2] - 2
     else
       Result := 2 * TenPowers[Pow div 2] - 2;
   end;
 
 var
   DigCnt, HalfCnt: Integer;
   AStart, ARevStart, AEnd, AMed, OddityMul, StartMul: Int64;
 begin
   DigCnt := 0;
   AStart := MaxNumber;
   while AStart > 0 do
   begin
     AStart := AStart div 10;
     Inc(DigCnt) ;
   end;
   if DigCnt <= 1 then
   begin
     Result := MaxNumber;
     Exit;
   end;
   HalfCnt := DigCnt div 2;
   AStart := MaxNumber div TenPowers[HalfCnt];
   AEnd := MaxNumber mod TenPowers[HalfCnt];
   if Odd(DigCnt) then
   begin
     AMed := AStart mod 10;
     AStart := AStart div 10;
     OddityMul := 10;
   end
   else
   begin
     AMed := 0;
     OddityMul := 1;
   end;
   StartMul := AStart - TenPowers[HalfCnt - 1];
   ARevStart := 0;
   while AStart > 0 do
   begin
     ARevStart := ARevStart * 10 + AStart mod 10;
     AStart := AStart div 10;
   end;
   if ARevStart <= AEnd then Inc(AMed) ;
   Result := PalBeforeTenPower(DigCnt - 1) + StartMul * OddityMul + AMed;
 end;
 

Test data: MAXNUMBER = 10 000 000

Boris's speed result: 1689 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.