Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Java by (13.1k points)

Can anyone help me what is wrong in the following code, I was trying to check for the palindrome of a number:

public static void main(String args[]){

    System.out.println("Please enter an integer : ");

    int integer = new Scanner(System.in).nextInt();

    if(isPalindrome(integer)){

        System.out.println(integer + " is a palindrome");

    }else{

        System.out.println(integer + " is not a palindrome");

    }       

}

1 Answer

0 votes
by (26.7k points)

Basically, you can try with the following code:

public static boolean isPalindrome(int integer) {

    int palindrome = integer;

    int reverse = 0;

    // Compute the reverse

    while (palindrome != 0) {

        int remainder = palindrome % 10;

        reverse = reverse * 10 + remainder;

        palindrome = palindrome / 10;

    }

    // The integer is palindrome if integer and reverse are equal

    return integer == reverse; // Improved by Peter Lawrey

}

I hope this will help.

Want to become a Java expert? Join Java Certification now!!

Want to know more about Java? Watch this video on Java Training | Java Course for Beginners:

Related questions

0 votes
1 answer
0 votes
1 answer
asked Feb 9, 2021 in Java by dante07 (13.1k points)
0 votes
1 answer
0 votes
2 answers
asked Jul 9, 2019 in Java by Anvi (10.2k points)

Browse Categories

...