FileDocCategorySizeDatePackage
Palindrome.javaAPI DocExample2219Sun Jan 27 13:14:38 GMT 2002None

Palindrome

public class Palindrome extends Object
Compute the Palindrome of a number by adding the number composed of its digits in reverse order, until a Palindrome occurs. e.g., 42->66 (42+24); 1951->5995 (1951+1591=3542; 3542+2453=5995).

TODO: Do we need to handle negative numbers?

author
Ian Darwin, ian@darwinsys.com
version
$Id: Palindrome.java,v 1.8 2002/01/27 18:14:39 ian Exp $.

Fields Summary
public static boolean
verbose
protected static final int
MAX_DIGITS
The number of digits in Long.MAX_VALUE
static long[]
digits
Constructors Summary
Methods Summary
static longfindPalindrome(long num)
find a palindromic number given a starting point, by calling ourself until we get a number that is palindromic.

		if (num < 0)
			throw new IllegalStateException("negative");
		if (isPalindrome(num))
			return num;
		if (verbose)
 			System.out.println("Trying " + num);
		return findPalindrome(num + reverseNumber(num));
	
static booleanisPalindrome(long num)
Check if a number is palindromic.


	       
	    
		// Consider any single digit to be as palindromic as can be
		if (num >= 0 && num <= 9)
			return true;

		int nDigits = 0;
		while (num > 0) {
			digits[nDigits++] = num % 10;
			num /= 10;
		}
		for (int i=0; i<nDigits/2; i++)
			if (digits[i] != digits[nDigits - i - 1])
				return false;
		return true;
	
public static voidmain(java.lang.String[] argv)


	     
		for (int i=0; i<argv.length; i++)
			try {
				long l = Long.parseLong(argv[i]);
				if (l < 0) {
					System.err.println(argv[i] + " -> TOO SMALL");
					continue;
				}
				System.out.println(argv[i] + "->" + findPalindrome(l));
			} catch (NumberFormatException e) {
				System.err.println(argv[i] + "-> INVALID");
			} catch (IllegalStateException e) {
				System.err.println(argv[i] + "-> " + e);
			} 
	
static longreverseNumber(long num)

		int nDigits = 0;
		while (num > 0) {
			digits[nDigits++] = num % 10;
			num /= 10;
		}
		long ret = 0;
		for (int i=0; i<nDigits; i++) {
			ret *= 10;
			ret += digits[i];
		}
		return ret;