9. Palindrome Number
🟩 Easy
Given an integer x
, return true
if x
is a palindrome, and false
otherwise.
An integer is a palindrome when it reads the same forward and backward.
For example, 121
is a palindrome while 123
is not.
Example 1
Input: x = 121 Output: true Explanation: 121 reads as 121 from left to right and from right to left.
Example 2
Input: x = -121 Output: false Explanation: From left to right, it reads -121. From right to left, it becomes 121-. Therefore it is not a palindrome.
Example 3
Input: x = 10 Output: false Explanation: Reads 01 from right to left. Therefore it is not a palindrome.
Constraints
-2^31 <= x <= 2^31-1
Solution
My Solution (Full Reversal)
Optimal Solution (Half Reversal)
Approach Analysis
This problem can be solved in multiple ways:
Full Reversal (Your Solution):
Reverse entire number
Compare with original
Simple to understand
Handles all cases
Half Reversal (Optimal):
Only reverse half the digits
Compare middle when done
More efficient
Handles overflow naturally
Visualization of Both Approaches
Full Reversal Process (Your Solution)
Half Reversal Process (Optimal)
Complexity Analysis
Full Reversal (Your Solution)
Time: O(log₁₀n)
Process all digits
n is the input number
Each digit needs one iteration
Space: O(1)
Only use one extra variable
Constant extra space
No additional data structures
Half Reversal (Optimal)
Time: O(log10n)
Process half the digits
Slightly faster in practice
Early termination possible
Space: O(1)
Only use reversed number
Constant extra space
No risk of overflow
Why Half Reversal Works
Mathematical Insight:
Palindrome is symmetric
Only need to check half
Middle digit doesn't matter
Works for both even/odd lengths
Optimization Benefits:
Half the operations
No overflow possible
Early termination
Handles edge cases elegantly
When to Use Each Approach
Full Reversal When:
Learning number manipulation
Code clarity is priority
Need the full reversed number
Teaching basic concepts
Half Reversal When:
Performance is critical
Large numbers expected
Memory constraints
Production code
Common Patterns & Applications
Related Problems:
Reverse Integer
Valid Palindrome
Palindrome Linked List
Palindrome Pairs
Key Techniques:
Digit manipulation
Two-pointer concept
Number reversal
Middle finding
Interview Tips
Solution Highlights:
Handle negative numbers
Consider trailing zeros
Optimize for half comparison
No string conversion needed
Common Pitfalls:
Missing negative check
Overflow issues
Wrong middle handling
Edge cases with zero
Testing Strategy:
Single digit
Even length numbers
Odd length numbers
Negative numbers
Numbers ending in zero
Follow-up Questions:
Handle decimal numbers?
Different number bases?
Optimize space usage?
Stream of digits?
Last updated
Was this helpful?