🎨Now live: Try our Free AI Image Generation Feature

Description
The problem is to determine if a given integer x
is a palindrome. A palindrome is a number that reads the same backward as forward. For example, 121
is a palindrome, while 123
is not.
Intuition
To check if an integer is a palindrome, we can reverse its digits and compare the reversed number with the original number. If they are the same, the number is a palindrome; otherwise, it is not. Negative numbers are not palindromes since they have a negative sign at the beginning.
Approach
- Check if the number is negative. If it is, return
False
immediately since negative numbers cannot be palindromes. - Initialize
reverse
to 0, which will hold the reversed number. - Make a copy of the original number
x
for comparison later. - Use a while loop to reverse the digits of
x
: - In each iteration, multiplyreverse
by 10 and add the last digit ofx
toreverse
. - Remove the last digit fromx
by integer division by 10. - After the loop, compare the reversed number with the original number copy.
- Return
True
if they are equal, indicating that the number is a palindrome; otherwise, returnFalse
.
Complexity
Time Complexity:
O(d), where d
is the number of digits in x
. Each digit is processed once during the reversal.
Space Complexity:
O(1), since we only use a few extra variables for the reversal and comparison.
Code
C++
class Solution:
def isPalindrome(self, x: int) -> bool:
if x < 0:
return False
reverse = 0
xcopy = x
while x > 0:
reverse = (reverse * 10) + (x % 10)
x //= 10
return reverse == xcopy
Python
class Solution {
public:
bool isPalindrome(int x) {
if (x < 0) {
return false;
}
long reverse = 0;
int xcopy = x;
while (x > 0) {
reverse = (reverse * 10) + (x % 10);
x /= 10;
}
return reverse == xcopy;
}
};
Java
class Solution {
public boolean isPalindrome(int x) {
if (x < 0) {
return false;
}
int reverse = 0;
int xcopy = x;
while (x > 0) {
reverse = (reverse * 10) + (x % 10);
x /= 10;
}
return reverse == xcopy;
}
}
JavaScript
var isPalindrome = function (x) {
if (x < 0) {
return false;
}
let reverse = 0;
let xcopy = x;
while (x > 0) {
reverse = (reverse * 10) + (x % 10);
x = Math.floor(x / 10);
}
return reverse === xcopy;
};