import java.lang.StringBuilder; public class Palindrome { /* determines whether or not an integer is a palindrome; that is, if it reads the same from both ways */ public static boolean isPalindrome(int n) { String s = String.valueOf(n); StringBuilder reverseString = new StringBuilder(); // reverse the string for (int i = s.length() - 1; i > -1; i--) { reverseString.append(s.charAt(i)); } return reverseString.toString().equals(s); } /* using the reverse() method in the StringBuilder class instead of reversing the string through iterations */ public static boolean isPalindrome2(long n) { String s = String.valueOf(n); return new StringBuilder(s).reverse().toString().equals(s); } public static void main(String[] args) { System.out.println(isPalindrome(1)); // true System.out.println(isPalindrome(9009)); // true System.out.println(isPalindrome(90109)); // true System.out.println(isPalindrome(1212)); // false } }DOWNLOAD
Created: February 19, 2014
Last Updated: August 27, 2014
Completed in full by: Michael Yaworski