-1

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");
    }
}
Sнаđошƒаӽ
  • 16,753
  • 12
  • 73
  • 90
PraveenHarris
  • 799
  • 1
  • 7
  • 10
  • 1
    Possible duplicate of [Check string for palindrome](http://stackoverflow.com/questions/4138827/check-string-for-palindrome) – Brahmam Yamani Apr 01 '16 at 04:57
  • Take a look at my answer. I have shown two methods to check for palindrome. And don't forget to mark it as [accepted](http://stackoverflow.com/help/accepted-answer) it it helped you by clicking on the hollow tick next to the answer :) Accepting gives you reputation too. If you don't accept any answer, people may be reluctant to answer your future questions. – Sнаđошƒаӽ Apr 09 '16 at 13:02

2 Answers2

2

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!");
}
Sнаđошƒаӽ
  • 16,753
  • 12
  • 73
  • 90
0

Your code works, but handling the numbers digit by digit is simpler and more readable:

public static boolean isPalindromic(String num) {
    for(int i = 0, len = num.length() ; i < len/2 ; i++) {
        if(num.charAt(i) != num.charAt(num.charAt(len-i-1))) return false;
    }

    return true;
}
Maljam
  • 6,244
  • 3
  • 17
  • 30