Search code examples
javapalindrome

How to check if a number is a palindrome?


I wrote a piece of code for a class homework. However I thought it was quite long! Is there a more optimized way to do this?

String text = input.readLine();
int num = (text.length())/2;
double letter = (double)(text.length())/2;
String s1 = text.substring(0,num);
int u1 = Integer.parseInt(s1);      

if (letter%1==0) {           
    StringBuffer s2 = new StringBuffer(text.substring(num));
    s2 = s2.reverse();
    String t2 = s2.toString();
    int u2 = Integer.parseInt(t2);
    if (u1==u2) {
        System.out.println("Palindrome");
    } else {
        System.out.println("FAIL");
    }
} else {
    StringBuffer s2 = new StringBuffer(text.substring(num+1));
    s2= s2.reverse();
    String t2 = s2.toString();
    int u2 = Integer.parseInt(t2);
    if (u1==u2) {
        System.out.println("Palindrom");
    }else {
        System.out.println("FAIL");
    }
}

Solution

  • You don't need to convert the string back to number in order to compare them. You can use string's equals() method to check if they are equal. Check this out (with necessary changes this will work for any string though, not just numbers).

    int num = 12300321;
    String numString = String.valueOf(num);
    String reverseNumString = new StringBuilder(numString).reverse().toString();
    
    if(numString.equals(reverseNumString)) {
        System.out.println(num + " is a Palindrome!");
    }
    else {
        System.out.println(num + " is not a Palindrome!");
    }
    

    Output:

    12300321 is a Palindrome!
    

    Alternate method (using only number manipulation; will work for integers only)

    int num = 12300321;
    int numCopy = num;
    int reverseNumInt = 0;
    
    while(numCopy != 0) {
        reverseNumInt = reverseNumInt * 10 + numCopy % 10;
        numCopy /= 10;
    }
    if(reverseNumInt == num) {
        System.out.println(num + " is a Palindrome!");
    }
    else {
        System.out.println(num + " is not a Palindrome!");
    }