Search code examples
javastringintpalindrome

Checking whether an int is palindrome or not without converting into a string?


public class Palindrome {
    public static void main(String args[]) {
        int x = 121;
        int res = 0;
        while (x > 0) {
            res = res * 10 + (x % 10);
            x /= 10;
        }
        if (x - res == 0) {
            System.out.println("True" + res);
        } else
            System.out.println("False" + res);
    }
}

Hello! This code is to check if an integer is a palindrome without converting the int to a String. For some reason, the computer thinks res is not same as x though both represent the number 121. Appreciate your help and thanks in advance!


Solution

  • You were close. Here is a solution building on what you did:

    static bool isPalindrome (int n1, int n2) {
        return getReverseInteger(n1) == n2;
    }
    
    static int getReverseInteger (int n) {
        int nReversed = 0;
        while (n > 0) {
          int digit = n % 10;
          nReversed = nReversed * 10 + digit;
          n = (n - digit) / 10;
        }
        return nReversed;
    }