‹ All Computer Science notes
ISC Practicals and Theory - Palindrome Number
Updated 20 Oct 2026
A Palindrome Number is a number that reads the same from left to right and from right to left. This program decides it by building the reverse of the number with arithmetic and comparing it with the original, all inside main.
Definition
A number is a Palindrome Number if it is equal to the number formed by writing its digits in reverse order.
- $121$ reversed is $121$, so it is a palindrome.
- $123$ reversed is $321$, which is not equal to $123$, so it is not a palindrome.
A single digit number such as $7$ is always a palindrome.
Algorithm
- Accept the number
n. Ifnis negative, printInvalid inputand stop. - Copy
nintotso that the original is kept, and setrev = 0. - Repeat while
t > 0:- Extract the last digit:
d = t % 10. - Append it to the reverse:
rev = rev * 10 + d. - Remove the last digit:
t = t / 10.
- Extract the last digit:
- If
rev == n, print that the number is a Palindrome Number, otherwise print that it is not.
Program
The whole logic is in main: it reads n, reverses a copy of it in a while loop and compares.
import java.util.Scanner;
public class PalindromeMain
{
public static void main(String args[])
{
Scanner sc = new Scanner(System.in);
System.out.print("Enter a number: ");
int n = sc.nextInt();
if (n < 0)
{
System.out.println("Invalid input");
}
else
{
int t = n, rev = 0, d;
while (t > 0)
{
d = t % 10;
rev = rev * 10 + d;
t = t / 10;
}
if (rev == n)
System.out.println(n + " is a Palindrome Number");
else
System.out.println(n + " is not a Palindrome Number");
}
}
}Variable description table
| Variable | Data Type | Purpose |
|---|---|---|
| args | String[] | Command line arguments of main (not used) |
| sc | Scanner | Reads the number typed by the user |
| n | int | The number entered by the user |
| t | int | Copy of n whose digits are removed one by one |
| rev | int | Stores the reverse of the number being built |
| d | int | Stores the last digit of t in each pass |
Sample input and output
Sample 1
Enter a number: 12321
12321 is a Palindrome NumberSample 2
Enter a number: 123
123 is not a Palindrome NumberSample 3
Enter a number: -5
Invalid inputDry run
Input: n = 123. At the start t = 123, rev = 0.
| Pass | t (before) | d = t % 10 | rev = rev * 10 + d | t = t / 10 |
|---|---|---|---|---|
| 1 | 123 | 3 | 3 | 12 |
| 2 | 12 | 2 | 32 | 1 |
| 3 | 1 | 1 | 321 | 0 |
Now t = 0, so the loop ends. rev = 321 is not equal to n = 123, so the output is 123 is not a Palindrome Number, the same as the real run above.
Variations
- Range "Accept two numbers m and n and display all the Palindrome Numbers between m and n."
- Palindrome Prime "Display the numbers in a range which are both prime and palindrome."
- Palindrome Word "Accept a word and check whether it is a palindrome."