EasyNo. 0009

Palindrome Number — LeetCode 9 Python Solution

Topics
Math
On a study list
Top Interview 150
Reading time
2 min

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

PythonSolution
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

Time
O(log_10(n)), where n is x
Space · auxiliary
O(1)

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

Related problems
No.ProblemDifficulty
0007Reverse IntegerMedium
0002Add Two NumbersMedium
0043Multiply StringsMedium
0048Rotate ImageMedium
0050Pow(x, n)Medium
0060Permutation SequenceHard

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.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity, invisible to screen sharing.

Free to download. Check it runs on your machine, then pick a plan.