Example
Input
121
Output
It is a palindrome
Algorithm to Check if a Number is a Palindrome
Input:
- Take an integer input from the user.
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.
Reverse the Number:
Use a
while
loop to reverse the digits of the number.In each iteration of the loop:
Update
rev
torev * 10 + a % 10
.Update
a
toa / 10
.
Check for Palindrome:
After the loop, compare
rev
withnum
.If
rev
is equal tonum
, 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 innum
.Step 3: The
while
loop runs as long asa
is not 0. In each iteration:The last digit of
a
is appended torev
.The last digit is removed from
a
.
Step 4: After reversing the number, we compare
rev
withnum
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.