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.
Constraints:
-231 <= x <= 231 - 1
Follow up: Could you solve it without converting the integer to a string?
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
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;
}
}
/**
* @param {number} x
* @return {boolean}
*/
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;
};
func isPalindrome(x int) bool {
if x < 0 {
return false
}
result := 0
y := x
for y != 0 {
result = result * 10 + y%10
y /= 10
}
return result == x
}
impl Solution {
pub fn is_palindrome(x: i32) -> bool {
if x < 0 {
return false;
}
let s = x.to_string();
let bs = s.as_bytes();
let n = bs.len();
let mut l = 0;
let mut r = n - 1;
while l < r {
if bs[l] != bs[r] {
return false;
}
l += 1;
r -= 1;
}
true
}
}
impl Solution {
pub fn is_palindrome(mut x: i32) -> bool {
if x < 0 || (x % 10 == 0 && x != 0) {
return false;
}
let mut y = 0;
while x > y {
y *= 10;
y += x % 10;
x /= 10;
}
x == y || x == y / 10
}
}