Palindrome Number — LeetCode 9 Python Solution
EasyMath
- Problem
- #9
- Pattern
- Math and Number Theory
- Reading time
- 2 min
- Source
- leetcode.com
The problem
Given an integer x, return true if x is a palindrome, and false otherwise.
Example
- Input
- x = 121
- Output
- true
- Explanation
- 121 reads as 121 from left to right and from right to left.
Python solution
Python
class Solution:
def isPalindrome(self, x: int) -> bool:
if x < 0 or (x and x % 10 == 0):
return False
y = 0
while y < x:
y = y * 10 + x % 10
x //= 10
return x in (y, y // 10)Complexity
| Measure | Complexity |
|---|---|
| Time | O(\log_{10}(n)), where n is x |
| Space | O(1) auxiliary |
Pattern: Math and Number Theory
Find the closed form, the invariant, or the modular identity — and skip the loop entirely. LeetCode 9. Palindrome Number is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Math.
The math and number theory guide has the Python template for the pattern and the 485 LeetCode problems that use it.
Related problems
On a study list
This problem is on Top Interview 150.
Frequently asked questions
- How hard is LeetCode 9. Palindrome Number?
- LeetCode 9. Palindrome Number is rated Easy on LeetCode.
- What is the time complexity of LeetCode 9. Palindrome Number?
- The Python solution on this page runs in O(\log_{10}(n)), where n is x.
- What is the space complexity of LeetCode 9. Palindrome Number?
- The Python solution on this page uses O(1) auxiliary space.
- What topics does LeetCode 9. Palindrome Number cover?
- LeetCode 9. Palindrome Number is tagged Math on LeetCode.