We can solve this without converting the number to a string by reversing the digits of the integer (or half of it to avoid overflow).
- If
x < 0or (x % 10 == 0andx != 0), return False. - Initialize
rev = 0. - While
x > rev:rev = rev * 10 + x % 10.x //= 10.
- Return
Trueifx == rev(even length) orx == rev // 10(odd length).
- Time Complexity: O(log N).
- Space Complexity: O(1).
def is_palindrome(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