Java program to determine whether a given number is a palindrome number or not

Problem:
Write a program to input a number from the user and tell whether it is a palindrome number or not. A palindrome number is a number that is same after reverse.
For example: 545, 151, 34543. 343, 1123211 are palindrome numbers.

Code:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
 /**
  * @author Hafiz Muhammad Umer
  */
 import java.util.Scanner;
 public class PalindromeNumber 
 {
     public static void main(String[] args) 
     {
         Scanner in=new Scanner(System.in);
         System.out.print("Enter a number: ");
         int a=in.nextInt(),b=0,c,d=a;
         while (a!=0)
         {
             c=a%10;
             b*=10;
             b+=c;
             a-=c;
             a/=10;
         }
         System.out.print("This is");
         if (b!=d)
             System.out.print(" not");
         System.out.println(" a palindrome number.");
     }
 }

Output:

Enter a number: 11569
This is not a palindrome number.

Enter a number: 1152511
This is a palindrome number.

Explanation:

  • The program inputs a number from the user at line 11 in the variable a.
  • The variable b defined at line 11 will be used to store the value in the variable a with its digits reversed. This is achieved in the while loop from line 12 to 19.
  • Then the input is compared to its reverse and the reslt is displayed accordingly

Leave a Comment