java

Check if a number is a palindrome in Java

In this tutorial, we are going to see how to check if a number is a palindrome in Java. A number is a palindrome if it is written the same way after reversing it.
 
Examples:

232, 191, 22022, 111, 666, etc.

 

Program Logic
  • Get the number to check
  • Keep the number in a temporary variable
  • Reverse the number
  • Compare the temporary number with the reversed number
  • If the two numbers are the same, display “the number is a palindrome”
  • Otherwise, display “the number is not a palindrome”

 

 

Program to check if a number is a palindrome in Java :
public class Palindrome {

    public static void main(String[] args) {

        int nbr = 191, reversedNBR = 0, reste, originNBR;

        originNBR = nbr;

        // reversed integer is stored in variable 
        while( nbr != 0 )
        {
            reste = nbr % 10;
            reversedNBR = reversedNBR * 10 + reste;
            nbr  /= 10;
        }

        // palindrome if originNBR and reversedNBR are equal
        if (originNBR == reversedNBR)
            System.out.println(originNBR+" is a palindrome.");
        else
            System.out.println(originNBR+" is not a palindrome.");
    }
}

Output:

191 is a palindrome.
mcqMCQPractice competitive and technical Multiple Choice Questions and Answers (MCQs) with simple and logical explanations to prepare for tests and interviews.Read More

Leave a Reply

Your email address will not be published. Required fields are marked *