0%

9. Palindrome Number

O(1) time O(1) space

1
2
3
4
5
6
7
8
9
class Solution:
def isPalindrome(self, x: int) -> bool:
if x == 0: return True
if x < 0 or x % 10 == 0: return False
y = 0
while x > y:
y = y * 10 + x % 10
x //= 10
return x == y or x == y // 10
1
2
3
4
5
6
7
8
9
10
11
12
class Solution {
public:
bool isPalindrome(int x) {
if (x < 0 || x != 0 && x % 10 == 0) return false; // 负数和结尾是0的正数都不合法
int y = 0;
while (x > y) {
y = y * 10 + x % 10;
x /= 10;
}
return x == y || x == y / 10;
}
};