AlgoViz

Palindrome Number

Easy

Reverse it and compare

Problem

Given an integer, return true if it reads the same forwards and backwards.

In simple words

Reverse the number and check if it matches the original, like a mirror.

The idea

Reverse the digits with the same pop-and-append loop and check whether the result equals the original. Reversing only half the digits and comparing the two halves avoids overflow entirely, which is the version interviewers like.

The trick

  • Any negative number is not a palindrome because of the leading minus.
  • Half-reversal: stop when the reversed part is at least the remaining part.

This one walks through the worked example rather than tracing the algorithm frame by frame — a full walkthrough is still to be drawn. The code and the idea below are the real solution.

121
0

Step 1 of 2. Here's the example — n = 121 Values: 121.

1/2
Optimal
timeO(log n)spaceO(1)
1original = n, rev = 02while n > 0:3  rev = rev * 10 + n % 104  n = n / 105return rev == original

Input

array
[121]

Output

answer

Check yourself

3 quick questions about this walkthrough. A wrong answer costs nothing.

Examples

Example 1

Input:
n = 121
Output:
true
Explanation:
121 reads the same forwards and backwards.

Example 2

Input:
n = 123
Output:
false
Explanation:
123 backwards is 321, which is different.

Example 3

Input:
n = 7
Output:
true
Explanation:
A single digit is always a palindrome.

Finished the walkthrough? Add it to your streak.