Skip to content
LEETFLIX

Palindrome Number

EasyMath
Solve on LeetCode

Easy · reverse the digits. Real solution for this problem — same player as the hand-authored deep-dives.

01

Problem

Read the prompt, flip through the examples, then steal the idea.

LeetCode 9. Palindrome Number. The copyrighted prompt is on LeetCode. This page is a working reverse the digits for this problem: editable input, Python, Go, and a step-by-step animation.

Constraints

  • —Player inputs are capped so the animation stays readable.
  • —Match LeetCode's own constraints when you submit there.

Examples

Input

x =
121

Output

true

02

Solution

Python and Go. The walkthrough below runs this same code.

Approach 1Optimal▶ Animated

Reverse and compare

Negatives are not palindromes (the minus sign). Reverse the digits of a non-negative x and compare.

Reversing 121 yields 121. Reversing 10 yields 01 → 1. No string conversion required.

Algorithm

  1. If x < 0, return false.
  2. Build rev by popping digits off x into rev * 10 + digit.
  3. Compare rev to the original.
Time
O(log x)
Space
O(1)
Solution.py
class Solution:    def isPalindrome(self, x: int) -> bool:        if x < 0:            return False        orig, rev = x, 0        while x:            rev = rev * 10 + x % 10            x //= 10        return rev == orig
Watch this run

03

Interactive walkthrough

Playing “Reverse and compare”. Edit the input, hit Run, then scrub.

Approach: Reverse and compare

Loading animation…