Given an integer x
, return true
if x
is a palindrome, and false
otherwise.
Example 1:
Input: x = 121 Output: true Explanation: 121 reads as 121 from left to right and from right to left.
Example 2:
Input: x = -121 Output: false Explanation: From left to right, it reads -121. From right to left, it becomes 121-. Therefore it is not a palindrome.
Example 3:
Input: x = 10 Output: false Explanation: Reads 01 from right to left. Therefore it is not a palindrome.
JAVA
Class Solution {
public boolean isPalindrome(int x) {
if (x < 0) return false;
int y = 0, t = x;
while (t != 0) {
y = y * 10 + t % 10;
t /= 10;
}
return x == y;
}
}
C++
class Solution {
public:
bool isPalindrome(int x) {
if (x < 0) return false;
long long a = x, b = 0;
while (x) {
b = b * 10 + x % 10;
x /= 10;
}
return a == b;
}
};
PYTHON
class Solution:
def isPalindrome(self, x: int) -> bool:
if x < 0:
return False
y, t = 0, x
while t:
y = y * 10 + t % 10
t //= 10
return x == y
JAVASCRIPT
var isPalindrome = function (x) {
let str = x + '';
let left = 0,
right = str.length - 1;
while (left < right) {
if (str[left] != str[right]) return false;
left++;
right--;
}
return true;
};