Palindrome Number · Optimal Solution

Reverse half the digits, compare the mirror.

A palindrome reads the same forwards and backwards. Instead of converting to a string or reversing all digits — risking overflow — reverse only the trailing half of the number and compare it with the remaining leading half. When the two halves meet in the middle, the loop stops. For even-length numbers, the halves must match exactly. For odd-length numbers, the middle digit is dropped from the reversed half before comparing. O(log₁₀ n) time. O(1) space.


Interactive

Watch the halves converge


Concept

Why reverse only half?

Full reversal requires building the entire reversed number, which can overflow for large integers. Half reversal avoids this by stopping as soon as the reversed portion meets or exceeds the remaining portion — processing at most half the digits.

half reversal

Peel digits from the trailing end one at a time, building the reversed half. Stop when the reversed half is at least as large as the remaining leading half.

midpoint detection

The loop condition leading > reversed naturally stops at the midpoint. For odd-length numbers, the reversed half absorbs the center digit.

no string conversion

Working purely with integer arithmetic avoids string allocation and character-by-character comparison. The solution uses only division and modulo.


Algorithm

Guard, reverse, compare

Two guard checks eliminate impossible palindromes instantly. Then a tight loop reverses the trailing half until it meets the leading half.

  1. 1

    Reject negatives

    A negative number has a minus sign that can never mirror. Return false immediately.

  2. 2

    Reject trailing zeroes

    If the number ends in 0 but isn't 0 itself, it would need a leading zero to mirror — impossible. Return false.

  3. 3

    Reverse the trailing half

    While leading > reversed: peel the last digit of the leading half with % 10, append it to the reversed half with × 10 + digit, and shrink the leading half with ÷ 10.

  4. 4

    Compare the halves

    Even length: leading == reversed. Odd length: leading == reversed / 10 — the integer division drops the absorbed middle digit.


Edge Cases

Guard rails that matter

Two early-exit guards and one boundary case ensure correctness before the reversal loop ever runs.

Negative numbers

The minus sign cannot appear at both ends. Every negative value is rejected before reversal begins — no arithmetic needed.

Trailing zeroes

A number like 10 ends in zero but doesn't start with zero. Without the guard, the half-reversal loop would incorrectly accept it because the leading zero is silently dropped during integer division.

Zero itself

Zero passes the trailing-zero guard because value != 0 fails. The reversal loop sees 0 > 0 as false and skips entirely. Both halves are 0 — an exact match.