Palindrome Number
Math
Problem Statement
Given an integer x
, return true
if x
is a palindrome, and false
otherwise.
Example
Example 1:
Input: x = 121
121121
The number is a palindrome.
Output: true
Explanation: 121 reads as 121 from left to right and from right to left.
Solution (Revert Half the Number)
The core idea is to revert the second half of the number and compare it with the first half. If they are the same, the number is a palindrome.
We can do this by repeatedly taking the last digit of the number and adding it to a new 'reverted' number. We stop when the original number is less than or equal to the reverted number.
Algorithm Steps
- Handle edge cases: negative numbers are not palindromes. If the last digit is 0, the number must be 0 to be a palindrome.
- Initialize a
revertedNumber
to 0. - Loop while the original number
x
is greater thanrevertedNumber
. - In each iteration, get the last digit of
x
and append it torevertedNumber
. - Remove the last digit from
x
. - After the loop, compare
x
andrevertedNumber
. If the number has an odd number of digits, the middle digit will be at the end ofrevertedNumber
, so we can ignore it by doingrevertedNumber / 10
.
Remaining (x)
121
→
Reverted
0
Start with the original number and a reverted number of 0.
Palindrome Number Solution