LeetCode #9 Easy

Palindrome Number

Palindrome Number is LeetCode 9 (Easy). Given an integer x, return true if it reads the same from left to right as from right to left, and false otherwise.

  • A negative number is never a palindrome: the minus sign sits on the left only.
  • x fits in a signed 32-bit integer.
  • The follow-up asks you to solve it without turning x into a string.
Constraints
  • -2³¹ <= x <= 2³¹ - 1
mathtwo-pointers
Open on LeetCode ↗
02

Intuition

A number is a palindrome when its right half, read backwards, equals its left half. You can read the right half backwards with arithmetic: x % 10 is the last digit and x // 10 drops it. Move digits one at a time from the end of x onto the end of a new number rev.

Stop as soon as rev is no longer smaller than x. At that moment half the digits have moved, so x is the left half and rev is the right half reversed. With an odd number of digits, rev holds the middle digit as its last digit, and the middle digit always matches itself, so drop it with rev // 10 before comparing.

How to spot this pattern

Comparing a sequence with its own reverse only needs half the work: compare the first half with the reversed second half. For an integer, the digits come off the right end with % 10 and // 10.

03

Approach

Try it first

Before reading on, decide how to tell, without counting digits, that you have taken exactly half of them off the right side of x. Then check what happens with 10 and with 0. Aim for O(log x) time and O(1) space.

1

Reject negatives and trailing zeros

Return false if x < 0, or if x ends in 0 but is not 0 itself. A number ending in 0 would need to start with 0 to be a palindrome, and only 0 does. The reversing loop cannot see this case, because a reversed half never has a leading zero.

2

Move digits from x to rev

While x > rev, append the last digit of x to rev with rev = rev * 10 + x % 10, then remove it with x //= 10. Each pass shortens x by one digit and lengthens rev by one.

3

Stop in the middle

The loop ends once rev >= x. If the number was a palindrome, the two halves are then equal (even length) or rev is one digit longer (odd length). If it was not, stopping early is still safe: the halves already differ, and comparing them gives false.

4

Compare the halves

Return x == rev or x == rev // 10. The first test covers an even count of digits. The second drops the middle digit that rev picked up when the count is odd.

04

Code in Python, C++ and Java

▶1class Solution:
▶2 def isPalindrome(self, x: int) -> bool:
▶3 if x < 0 or (x % 10 == 0 and x != 0):
▶4 return False
▶5 rev = 0
▶6 while x > rev:
▶7 rev = rev * 10 + x % 10
▶8 x //= 10
▶9 return x == rev or x == rev // 10
xrev1221first: negative, or ends in 0?
x1221
Two kinds of number can be ruled out before any work: negatives, because the minus sign has no partner on the right, and numbers ending in 0 other than 0 itself, because no number starts with 0.
xrev1221move 1 → x is 122, rev is 1, keep going
x122
rev1
The last digit of 1221 is 1. It goes onto the right end of rev, and x loses it. x is still bigger than rev, so fewer than half the digits have moved.
xrev1212move 2 → x is 12, rev is 12, stop
x12
rev12
The last digit of 122 is 2. It goes onto the right end of rev, and x loses it. Now rev is at least x, so half of the digits have moved and the loop ends.
xrev121212 equals 12 → true
x12
rev12
returntrue
Both halves have the same length. The left half equals the reversed right half, so the number reads the same both ways.
05

Compare the string with its reverse

The shortest way to check a palindrome number in Python is to compare str(x) with its reverse, str(x)[::-1]. A minus sign lands at the wrong end after reversing, so negatives fail without a special case. It builds a string of up to 11 characters, which is why it misses the follow-up.

▶1class Solution:
▶2 def isPalindrome(self, x: int) -> bool:
▶3 s = str(x)
▶4 return s == s[::-1]
06

Common pitfalls

Reversing the whole number in a 32-bit int

✗ Wrong
int rev = 0;
while (x > 0) { rev = rev * 10 + x % 10; x /= 10; }
✓ Right
int rev = 0;
while (x > rev) { rev = rev * 10 + x % 10; x /= 10; }

Reversing all the digits of x = 2147483647 gives 7463847412, which does not fit in an int and overflows in C++ and Java. Stopping in the middle keeps rev at five digits.

Leaving out the trailing zero check

✗ Wrong
if x < 0:
    return False
✓ Right
if x < 0 or (x % 10 == 0 and x != 0):
    return False

For x = 10 the loop moves the 0 first: rev = 0, x = 1, then moves the 1: rev = 1, x = 0. Now x == rev // 10 is 0 == 0, so the code returns true, but 10 reads 01 backwards.

07

Edge cases

x = 0

It ends in 0 but is 0 itself, so it passes the first check. The loop does not run because 0 > 0 is false, and x == rev returns true.

A single digit, like x = 7

One pass moves the 7, leaving x = 0 and rev = 7. Then x == rev // 10 is 0 == 0, so every single digit is a palindrome.

08

Complexity

Time
O(log x)
Space
O(1)
x has about log₁₀ x digits, at most 10 within the constraints, and the loop handles half of them. Only two integers are stored.
09

Palindrome Number FAQ

Is −121 a palindrome?

No. Read from right to left it is 121−, which is not a number equal to −121. Every negative value returns false.

How is this different from checking a palindrome string?

With a string you can point at both ends and walk inwards, as in Valid Palindrome. An integer only lets you take digits off the right end cheaply, so you rebuild the right half backwards instead of reading from the left.