Search code examples
javapalindrome

Is this Java palindrome solution efficient? It doesn't use string or char methods


Here's the solution I saw:

package com.philippemoisan;

public class Main {

    public static void main(String[] args) {
        System.out.println(isPalindrome(-212));
    }

    public static boolean isPalindrome(int number)  {
        int reverse  = 0;
        int initNumber = number;
        while (number != 0)  {
            int lastDigit = number % 10;
            reverse = reverse * 10;
            reverse +=lastDigit;
            number/=10;
        }
        if (initNumber == reverse)  {
            return true;
        }
        return false;
    }
}

I know there are palindrome solutions here but I am not that far in my Java course yet. So, I just want to know if the solution I posted here is efficient, or would it a lot better to use the solutions from the thread link I provided.


Solution

  • The solution on the linked answer is more efficient, because if the word is not palindrom, it will not iterate through the entire number/word.

    The solution you provided loops through the entire number/word even when the first step can detect that the first and the last digit/char are not identical.