Method Returning False but expected true [closed]

Tags: ,



The below code is for reversing a 3 digit number and then checking while they are equal. Main method

public class Main {
    public static void main(String[] args) {
       boolean result= NumberPalindrome.isPalindrome(121);
        System.out.println(result);

    }
}

Method for reversing number

public class NumberPalindrome {
    public static boolean isPalindrome(int number){
        int reserve=100;
        int reverseNumber=0;
        while (number>0){
            int lastDigit=(number%10);
            reverseNumber+=(lastDigit*reserve);
            reserve/=10;
            number/=10;
        }
        System.out.println("reverse number"+reverseNumber);
        if (reverseNumber==number){
            return true;
        }else {
            return false;
        }
    }
}

I have given a print statement right after the while loop ends and that print gives correct expected value but the if statement gives false even when it has to be true.

Answer

public static boolean isPalindrome(int input) {
    int reserve = 100;
    int reverseNumber = 0;
    int number = input;

    while (number > 0) {
        int lastDigit = (number % 10);
        reverseNumber += (lastDigit * reserve);
        reserve /= 10;
        number /= 10;
    }

    System.out.println("reverse number" + reverseNumber);
    System.out.println("original number" + input);
    return reverseNumber == input;
}

Because you modified your input param number in number /= 10



Source: stackoverflow