Palindrome Number

Easy

Topics
Math

Given an integer n, return true if it is a palindrome (reads the same backward as forward). Negative numbers are not palindromes.

Example 1

102112
Every digit matches its mirror, so the answer is true. Reversing only half the number and comparing avoids the overflow that reversing the whole of it risks.
Cells are the decimal digits, with their positions below.
Input:  n = 121
Output: true

Example 2

-0112213
The shaded digits differ from their mirror position, so the answer is false. A minus sign can never mirror, which is why every negative number fails immediately.
Input:  n = -121
Output: false

Example 3

1001
Input:  n = 10
Output: false

Constraints

  • -2^31 <= n <= 2^31 - 1
Editorial — intuition, approach, complexity and pitfalls

Intuition

A number is a palindrome exactly when it equals its own digit-reversal. Negatives never qualify because of the leading minus sign.

Approach

  1. If negative, return False.
  2. Reverse the digits (or compare the string form with its reverse).
  3. Return whether they match.

Walkthrough

n = 121 -> "121" reversed "121" -> true
n = -121 -> negative -> false
n = 10  -> "10" vs "01" -> false

Complexity

  • Time — O(d): proportional to the digit count d.
  • Space — O(1): reversing half the number arithmetically avoids the string entirely for a strict O(1) solution.

Common Pitfalls

  • Reverse only the back half. The loop ends when rev catches n, which is why nothing can overflow -- a full reversal of a 32-bit palindrome can, and that is the trap the problem is set around.
  • Odd digit counts need n == rev // 10 as well. Comparing only n == rev handles even lengths and reports 121 as not a palindrome.
  • A note on the negative guard: in this Python form it is documentation rather than correctness. while n > rev is already false for any negative, so -121 returns false with or without it -- verified. Keep it anyway, because the other language tabs do not all share Python's modulo behaviour, and the intent should be visible.

Full Solution — all languages

class Solution:
    def isPalindrome(self, n):
        # Negatives read as -121 vs 121-, never palindromes.
        if n < 0:
            return False
        # A trailing zero would need a leading zero to match, which no number has.
        # (0 itself is the exception.)
        if n % 10 == 0 and n != 0:
            return False
        # Reverse only the back half. The loop stops when rev catches up to n, which
        # happens at the midpoint -- so no full reversal, and nothing can overflow
        # because rev never grows past n.
        rev = 0
        while n > rev:
            rev = rev * 10 + n % 10
            n //= 10
        # Even digit count: the halves match exactly.
        # Odd: rev carries the middle digit, so drop it before comparing.
        return n == rev or n == rev // 10
SensAI
Beta
Tap the mic to stop voice mode