LeetCode 9 · Bits · Math

Palindrome Number, explained with a picture

Folding a number strip in half.

Bits · Math
▶ Watch it step by step

The problem

Decide whether an integer reads the same forwards and backwards.

Input:  12321
Output: true

Picture it

Picture folding a number strip in half. Peel digits off the end of the number to build its reverse, but stop at the middle. Then compare the two halves (ignoring the middle digit for odd lengths).

Short version: the full lesson (brute force, complexity, edge cases and a quiz) is still being written. The animation is complete.

The key idea

Reverse half the number. O(log n), no string conversion.

Python solution

def is_palindrome(x):
    if x < 0 or (x % 10 == 0 and x != 0):
        return False
    rev = 0
    while x > rev:
        rev = rev * 10 + x % 10     # peel the last digit onto rev
        x //= 10
    return x == rev or x == rev // 10

In the interactive version each line lights up as the animation runs, and you can type your own input to see the algorithm handle it.