Check Palindromic Number in Java
Problem
A palindromic number is a number that reads the same forwards and backwards, the same idea as a palindromic string but checked with pure arithmetic instead of text.
Given a number, determine whether it is a palindrome.
Java Program
public class PalindromeNumberCheck {
public static void main(String[] args) {
int num = 12321;
int original = num;
int reversed = 0;
while (num > 0) {
int digit = num % 10; // read off the last digit
reversed = reversed * 10 + digit; // shift left and append the digit
num /= 10;
}
System.out.println(original + " is a palindrome: " + (reversed == original));
}
}Output
Core Logic
Rebuilding the number in reverse, one digit at a time using % and /, and comparing the result to the original checks the definition without ever touching a String.
- 1
originalkeeps a copy of the starting value, sincenumgets consumed digit by digit. - 2Each loop pass reads the last digit with
num % 10, then shiftsreversedleft by one decimal place and adds that digit:reversed = reversed * 10 + digit. - 3
num /= 10removes the digit that was just processed. - 4Once
numreaches0, every digit has been moved intoreversedin reverse order, and it's compared againstoriginal.
12321, digits 1, 2, 3, 2, 1 are read off in that order and rebuilt into reversed = 12321 — an exact match.Key Point: This is the arithmetic counterpart to reversing a string — the same digit-by-digit idea, just built from % and / instead of charAt().
Why: The loop runs once per digit, and only the running reversed value and the original are kept, regardless of how large the number is.
Key Concepts
Approach 2: String Reversal
public class PalindromeNumberString {
public static void main(String[] args) {
int num = 12321;
String str = String.valueOf(num);
// Reuses StringBuilder's built-in reverse(), the same technique used for string palindromes
String reversed = new StringBuilder(str).reverse().toString();
System.out.println(num + " is a palindrome: " + str.equals(reversed));
}
}
Output
Core Logic
Converting the number to a String and reusing StringBuilder's built-in reverse() sidesteps the arithmetic entirely.
- 1
String.valueOf(num)converts the number into its text representation. - 2
new StringBuilder(str).reverse().toString()flips the character order, the same technique used to reverse a string elsewhere on this site. - 3
str.equals(reversed)compares the original and reversed text directly.
12321, the string "12321" reverses to "12321" — identical, so the check returns true.Key Point: This is shorter to write than the arithmetic version, at the cost of converting the number to a String and back — worth it for a one-off check, less so in a tight loop over many numbers.
Why: Converting to a String and reversing it both allocate new objects proportional to the number's digit count, unlike the arithmetic version's constant extra space.