Dare2Solve
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.
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.
False
immediately since negative numbers cannot be palindromes.reverse
to 0, which will hold the reversed number.x
for comparison later.x
:
reverse
by 10 and add the last digit of x
to reverse
.x
by integer division by 10.True
if they are equal, indicating that the number is a palindrome; otherwise, return False
.O(d), where d
is the number of digits in x
. Each digit is processed once during the reversal.
O(1), since we only use a few extra variables for the reversal and comparison.
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
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;
}
};
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;
}
}
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;
};