Palindrome Number

EasyMath · Digit Manipulation🧩 Math & GeometryLeetCode #9 ↗Updated

Problem

Given a 32-bit signed integer x, decide whether its decimal representation reads the same forwards and backwards. The minus sign counts as a character, so every negative number is not a palindrome.
Inputx = 121Outputtrue
Inputx = -121Outputfalse
Inputx = 10Outputfalse

-231 ≤ x ≤ 231-1  ·  Follow-up: solve it without converting the integer to a string.

Try it yourself

Java
class Solution {
    public boolean isPalindrome(int x) {
        
    }
}
Your code is saved in this browser.Submit on LeetCode ↗
Key insight
You only need to reverse the back half of the digits: peel digits off x until the reversed part is ≥ what remains, then compare the two halves. No string, and no risk of overflow.
PatternMath & Geometry

Instinct Digits, factors, slopes or distances hide a formula - find the invariant, then guard against overflow, negatives and floating-point error.

Memory hack Mod peels, gcd reduces, squares compare - and long saves the day. Peel digits with %10, reduce slopes with gcd, compare squared distances.

Open the Math & Geometry guide →

Approaches

Brute ForceConvert to String + Two Pointers

Time O(log x)Space O(log x)

Turn x into its string form and walk two pointers inward, comparing characters. A negative number fails immediately because '-' never matches a digit. The string has ~log10x characters.

Java
public boolean isPalindrome(int x) {
    String s = Integer.toString(x);
    int left = 0, right = s.length() - 1;
    while (left < right) {
        if (s.charAt(left) != s.charAt(right)) return false;
        left++;
        right--;
    }
    return true;
}

Simplest to write, but allocates a string and ignores the follow-up.

At a glance

LevelApproachTimeSpace
Brute ForceConvert to String + Two PointersO(log x)O(log x)
BetterReverse All Digits (in a long)O(log x)O(1)
OptimalReverse Only Half the DigitsO(log x)O(1)
Common pitfalls
  • Forgetting negatives — -121 reversed is 121-, not a palindrome.
  • Reversing the whole int into an int can overflow for large inputs.
  • Skipping the trailing-zero check in the half-reverse version (10 → true).
Interview tips
  • Mention the string version first, then tackle the “no string” follow-up.
  • Explain why reversing half avoids overflow: rev has at most 5 digits.
  • Walk through one odd-length and one even-length example to justify rev / 10.
Pattern
Digit peeling (% 10, / 10) → reverse, sum or compare the digits of an integer without strings.
My notes saved in this browser