Palindrome Numbers

Viewed 54

I am writing Java code in which I have to create a method that returns boolean with one parameter. The code has to identify in true or false if the number (parameter) provided to it is palindrome or not. This is my code but the outcome is false all the time. Can someone identify what is wrong here?

public class NumberPalindrome {

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

    }

    public static boolean isPalindrome(int number) {
        int reverse = 0;
        boolean variable = true;
        while (number > 0) {
            int lastdigit = number % 10;
            reverse *= 10;
            reverse += lastdigit;
            number = number / 10;
        }
        if (reverse==number) {
            variable = true;
        } else variable = false;
        return variable;
    }
}
1 Answers

You must keep in memory the initial value of number given in parameter to be able to compare it later with reverse. The code will look like this.

public class NumberPalindrome {

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

    }

    public static boolean isPalindrome(int number) {
        int initialNumber = number;
        int reverse = 0;
        boolean variable = true;
        while (number > 0) {
            int lastdigit = number % 10;
            reverse *= 10;
            reverse += lastdigit;
            number = number / 10;
        }
        if (reverse==initialNumber) {
            variable = true;
        } else variable = false;
        return variable;
    }
}
Related