Number Palindrome
Problem Link : Number Palindrome
Problem Statement
You are given an integer n.
Determine whether it is a palindrome.
A number is a palindrome if it reads the same backward as forward.
Examples
Example 1:
-
Input:
n = 555 -
Explanation: 555 reversed is 555 → Palindrome
-
Output:
true
Example 2:
-
Input:
n = 123 -
Explanation: 123 reversed is 321 → Not a palindrome
-
Output:
false
Example 3:
-
Input:
n = 1221 -
Explanation: 1221 reversed is 1221 → Palindrome
-
Output:
true
Constraints
1 ≤ n ≤ 10⁹
Intuition
A number is a palindrome if reversing its digits results in the same number.
To check this, we:
-
Reverse the number using arithmetic operations (modulus and division).
-
Compare the reversed number with the original.
If both are equal, the number is a palindrome.
Approach
-
Store the original number in a variable
cpy. -
Initialize a variable
rev = 0to store the reversed number. -
Loop until
nbecomes 0:-
Extract the last digit using
n % 10. -
Append it to the reversed number:
rev = rev * 10 + digit. -
Remove the last digit:
n = n / 10.
-
-
Finally, compare
revwith the original numbercpy.
If they are equal, return true; otherwise, return false.
Java Code
class Solution {
public boolean isPalindrome(int n) {
int rev = 0;
int cpy = n; // Store the original number
while (n > 0) {
int r = n % 10; // Get the last digit
rev = rev * 10 + r; // Build the reversed number
n /= 10; // Remove last digit
}
return rev == cpy; // Compare reversed with original
}
}
Dry Run
Input: n = 121
cpy = 121,rev = 0
Step 1:
r = 1,rev = 0 * 10 + 1 = 1,n = 12
Step 2:
r = 2,rev = 1 * 10 + 2 = 12,n = 1
Step 3:
r = 1,rev = 12 * 10 + 1 = 121,n = 0
Final Check:
rev == cpy→121 == 121→true
Time Complexity
- O(log₁₀(n))
We process each digit once, and the number of digits islog₁₀(n).
Space Complexity
- O(1)
Constant space is used for variables.
Conclusion
This arithmetic approach to checking for a palindrome is both efficient and reliable, avoiding the need to convert the number to a string. It adheres to optimal time and space constraints and handles all valid positive integers within the given range.