Adsense 728 * 15

Search

Custom Search

Java Program to Check whether a Number is Palindrome or not

Write a java program to check whether a number is palindrome or not. Given an input number, we have to write a code to check whether a number is palindrome or not.

Before solving this problem, let's first understand what is palindrome number?

What is Palindrome Number? 


A palindrome number is a number that remains the same when its digits are reversed.

For example - 121, 454, 12521 etc.

If we reverse 121, it remains 121 so it's a palindrome number.

How do we check whether a number is palindrome or not


To check whether a number is palindrome or not, just reverse a number and compare with the input number. If it's equal then it's a palindrome number otherwise it's not.

C program to reverse a number

Reverse a number using recursion - C, C++ code

Java program to count number of digits in a number


Java Program to Check whether a Number is Palindrome or not


Java Program to Check whether a Number is Palindrome or not


To check whether a number is palindrome or not, we have to reverse a number and compare it with the input number. If both the numbers are equal then it's a palindrome number. Let's implement them programmatically.


public class Palindrome {

   public static void main(String[] args) {

      Scanner in = new Scanner(System.in);

      System.out.println("Enter an input number");
      int num = in.nextInt();

      // Assign number in temp
      int temp = num;
  
      int rev = 0, digit;
 
      // Logic to reverse a number
      while (temp > 0) {
 
        digit = temp % 10;
        rev = rev * 10 + digit;
        temp = temp / 10;
      }

      /*
       * If original and reverse of a number 
       * is equal then it's a palindrome number.
       */
       if (rev == num) {
         System.out.println(num + " is palindrome");
       } else {
         System.out.println(num + " is not a palindrome");
       }
   }

}


Output :


Palindrome program output

Palindrome program output











Program to reverse a string in java

Java program to print factorial of a number

No comments:

Post a Comment