Check if a Number is a Palindrome In Java

Example

Input

121

Output

It is a palindrome

Algorithm to Check if a Number is a Palindrome

  1. Input:

    • Take an integer input from the user.
  2. Initialize Variables:

    • Initialize rev to 0 (this will store the reversed number).

    • Create another variable num to store the original value of the input number.

  3. Reverse the Number:

    • Use a while loop to reverse the digits of the number.

    • In each iteration of the loop:

      • Update rev to rev * 10 + a % 10.

      • Update a to a / 10.

  4. Check for Palindrome:

    • After the loop, compare rev with num.

    • If rev is equal to num, print "It is a palindrome".

    • Otherwise, print "It is not a palindrome".

Java Implementation

import java.util.Scanner; 

public class PalindromeChecker {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in); 
        int a, rev = 0, num; 

        System.out.print("Enter the number: "); 
        a = sc.nextInt(); 
        num = a; 

        while (a != 0) {
            rev = (rev * 10) + a % 10; 
            a = a / 10; 
        }

        if (rev == num) {
            System.out.print("It is a palindrome"); 
        } else {
            System.out.print("It is not a palindrome"); 
        }

        sc.close();
    }
}

Explanation

  • Step 1: We use Scanner to read the input number from the user.

  • Step 2: We initialize rev to 0 and store the original number in num.

  • Step 3: The while loop runs as long as a is not 0. In each iteration:

    • The last digit of a is appended to rev.

    • The last digit is removed from a.

  • Step 4: After reversing the number, we compare rev with num to check if the original number and the reversed number are the same. If they are the same, it is a palindrome; otherwise, it is not.