Mr Plow
Posts: 18
Nickname: mrplow
Registered: Jun, 2003
|
|
Re: I need to create a numerical palindrome program
|
Posted: Jun 16, 2003 4:58 PM
|
|
Not the prettiest code, but it works.
public class Palindrome { public static void main(String[] args) { //The number to be tested... int x = 155;
//Loop through a maximum of 10 times for(int i = 1 ; i <= 10; i++) { //check if palindrome, if yes, print out result and break out of loop if(isPali(x)) {System.out.println(x + " is a palindrome\nIt took " + i + " times through the for loop to get this result."); break;} //check to make sure that you haven't already looped 10 times. if(i == 10) { System.out.println("After 10 iterations, this number: " + x + " is still not a palindrome... exiting"); break; } //reverse the number and add the reversed number to the orginal. Also print out what the program is doing so that the user //can follow what is happening StringBuffer sb = new StringBuffer(x + ""); StringBuffer sb2 = sb.reverse(); String s3 = sb2.toString(); int x2 = Integer.parseInt(s3); System.out.println("x = " + x); System.out.println("x reversed = " + x2); x += x2; System.out.println("x + x reversed = " + x); }//end of for loop }//end of main() method
//static method that can be called to see if a given number is a palidrome public static boolean isPali(int l) { String longAsString = l + ""; int x = longAsString.length(); //logic to handle single digit input if (x == 1) { return true; }
//logic to handle double digit input if(x == 2) { char x1 = longAsString.charAt(0); char x2 = longAsString.charAt(1); return x1 == x2; }
//logic to handle input with odd number of digits if( (x % 2) == 1) { //Remove middle char which doesn't need to match StringBuffer newString = new StringBuffer(); int xx = x; int y = (xx / 2); newString.append(longAsString.substring(0, y)); newString.append(longAsString.substring(y + 1)); String ss = newString.toString(); int xxx = ss.length(); for(int i = 0; i < xxx/2; i++) { char xFirst = ss.charAt(i); char xLast = ss.charAt(xxx - (i + 1)); if(xFirst != xLast) { return false; } } return true; }//end of if odd number of digits.
//logic to handle input with even number of digits if( (x % 2) == 0) { int xx = longAsString.length(); for(int i = 0; i < xx/2; i++) { char xFirst = longAsString.charAt(i); char xLast = longAsString.charAt(xx - (i + 1)); if(xFirst != xLast) { return false; } } return true; }//end of if even number of digits
//default return value return false; } };
|
|