The idea is as follows... Take a number ...say 54
Algorithm ...
Add <num> + Reverse(<num> ) ... should converge to a palindrome !
54 + 45 .... 99 is a palindrome
132 + 231 => 363 .. is a palindrome...
Some times..we need to continue this process untill we reach a palindrome..
The source code will tell the rest of the story..
////////////////////////////////////////////
//
// A C# Program to generate a Palindrome Number from
// a number... Adapted from Java CookBook...
//
// Recipe 5.21 Program:Number Palindrome...page 151
//
//
using System;
namespace Test
{
public class Caller {
////////////////////////////////////////////
//
// This will reverse a Long number
//
public static long Reverse( long a )
{
long rev = 0;
while ( a != 0 ) {
rev = rev*10 + a%10;
a=a/10;
}
return rev;
}
/////////////////////////////////////////////////////
//
//
// This will determine whether a number
// is palindrome or not
//
public static bool isPalindrome( long a ) {
if ( a.ToString() ==
Reverse(a).ToString() )
return true;
return false;
}
/////////////////////////////////////////////////////////
//
// Actual routine to Generate a Palindrome... it will converge !
//
//
public static long FindPalindrome( long a ) {
if ( isPalindrome(a) )
return a;
return FindPalindrome(
a + Reverse(a));
}
//////////////////////////////////////////
//
// entry Point ...
//
//
public static void Main(String [] args ) {
if ( args.Length != 1 ) {
Console.WriteLine("FindPalindrome <num>\n");
return;
}
long rs = 0;
try {
rs = Int64.Parse(args[0]);
}
catch( Exception e ) {
e.ToString();
}
if ( rs <= 0 ) {
Console.WriteLine("Invalid number\n");
return;
}
rs = FindPalindrome(rs);
Console.WriteLine(rs.ToString());
}
}
}
No comments:
Post a Comment