[
math
palindrome
]
Leetcode 0009 Palindrome Number
Problem statement
https://leetcode.com/problems/palindrome-number/
Solution
As we can not convert to string, we can extract the last digit and create new number, and do it several times, like $12323 \to 1232, 1 \to 123, 12$, and finally we check that $12$ is $123$ with removed last digit.
Complexity
Time complexity is just $O(n)$, where $n$ is length of number, space complexity is $O(1)$.
Code
class Solution:
def isPalindrome(self, x):
if x < 0 or (x%10 == 0 and x != 0): return False
rev = 0
while x > rev:
rev = rev*10 + x%10
x //= 10
return x == rev or x == rev//10