Posted onEdited onInLeetCodeDisqus: Symbols count in article: 388Reading time ≈1 mins.
O(1) time O(1) space
1 2 3 4 5 6 7 8 9
classSolution: defisPalindrome(self, x: int) -> bool: if x == 0: returnTrue if x < 0or x % 10 == 0: returnFalse 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
classSolution { public: boolisPalindrome(int x){ if (x < 0 || x != 0 && x % 10 == 0) returnfalse; // 负数和结尾是0的正数都不合法 int y = 0; while (x > y) { y = y * 10 + x % 10; x /= 10; } return x == y || x == y / 10; } };