🔗 Related Links
- 📝 My LeetCode Solution: 9. Palindrome Number
- 👤 My LeetCode Profile: zeeshan138 🚀
LeetCode Submission Results
Metric | Value | Percentile |
---|---|---|
Runtime | 3 ms | 98.66% |
Memory | 63.98 MB | 78.96% |
Explanation of Key Points
Early exits
- Any negative number is not a palindrome (e.g.,
-121
→false
). - Any number ending in
0
can’t be a palindrome unless it’s0
itself (e.g.,10
→false
).
Reversing half the number
- Iteratively remove the last digit from
x
and append it toreverted
. - Continue until the remaining part (
x
) is less than or equal to the reversed half (reverted
), meaning we've processed at least half of the digits.
Handling odd/even length
-
Even length: The two halves must match exactly (
x === reverted
). -
Odd length: The reversed half contains the middle digit, so drop it with
Math.floor(reverted / 10)
before comparing.
This approach satisfies LeetCode’s constraints (−2³¹ ≤ x ≤ 2³¹−1) and avoids any string conversions.
Complexity Analysis
Time Complexity:
The loop processes roughly half of the digits ofx
. Ifx
hasd
digits, it runs ~d/2
times → $$O(d) = O(\log_{10} x)$$.Space Complexity:
Only a constant number of integer variables are used → $$O(1)$$.
Code
javascript
/**
* @param {number} x
* @return {boolean}
*/
var isPalindrome = function(x) {
// Negative numbers or numbers ending with 0 (but not 0 itself) cannot be palindrome.
if (x < 0 || (x % 10 === 0 && x !== 0)) {
return false;
}
let reverted = 0;
// Reverse digits until the original number is <= reverted reversed half
while (x > reverted) {
reverted = reverted * 10 + (x % 10);
x = Math.floor(x / 10);
}
// For even length: x === reverted
// For odd length: x === Math.floor(reverted / 10)
return x === reverted || x === Math.floor(reverted / 10);
};
Top comments (0)