Palindrome Number
EasyReverse it and compare
Problem
Given an integer, return true if it reads the same forwards and backwards.
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.
Step 1 of 2. Here's the example — n = 121 Values: 121.
1original = n, rev = 02while n > 0:3 rev = rev * 10 + n % 104 n = n / 105return rev == originalInput
- 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.
Practice this problem:LeetCode(opens in a new tab)Search GeeksforGeeks(opens in a new tab)
Finished the walkthrough? Add it to your streak.