Matt Gerrans
Posts: 1153
Nickname: matt
Registered: Feb, 2002
|
|
Re: Interesting Palindrome problem
|
Posted: Jun 2, 2003 12:02 PM
|
|
Here is the answer I concocted, but never posted, when the question was first asked. Its the same idea as the last few posts: you don't need the brutish guess-and-test, you can just generate the correct results in the first place.
/*
* MirrorWorlds.java
*
* Simple demo of generating "palindrome" numbers.
*
* Copyright 2003, Matt Gerrans.
*
* Turning in this code as homework is a violation of ethical principals,
* and punishable by severe penalties, even if you change the variable
* names. Feeding it to your dog is acceptible.
*/
public class MirrorWorlds
{
public static long [] getMirrorNumbers( int digits )
{
boolean odd = digits % 2 == 1 ? true : false;
digits = digits / 2 + digits % 2;
long maxnum = (long)Math.pow( 10, digits );
long minnum = maxnum / 10;
StringBuffer reversed = new StringBuffer();
long [] mirrorNumbers = new long[(int)(maxnum-minnum)];
for( long i = minnum; i < maxnum; i++ )
{
reversed.setLength(0);
reversed.insert(0,i);
if(odd)
reversed.setLength( (int)digits - 1 );
reversed.reverse();
reversed.insert(0,i);
mirrorNumbers[(int)(i-minnum)] = Long.parseLong(reversed.toString());
}
return mirrorNumbers;
}
public static void main( String [] args )
{
int digits = 5;
if( args.length >= 1 )
try
{
digits = Integer.parseInt(args[0]);
}
catch( Exception e )
{
System.out.println( "Can't parse command line, so we'll stick with the default." );
}
long [] mirrorNumbers = getMirrorNumbers( digits );
System.out.println( "All " + digits + "-digit mirror-numbers:\n" );
for( int i = 0; i < mirrorNumbers.length; i++ )
System.out.print( mirrorNumbers[i] + " " );
}
}
|
|