Given an integer x, return true if x is palindrome integer.
An integer is a palindrome when it reads the same backward as forward.
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.
class Solution:
def isPalindrome(self, x: int) -> bool:
if x < 0:
return False
return str(x) == str(x)[::-1]
Time Complexity: O(N)
Space Complexity: O(N)
class Solution:
def isPalindrome(self, x: int) -> bool:
if x < 0:
return False
revX = 0
oriX = x
while oriX:
revX = (10*revX) + (oriX % 10)
oriX //= 10
return revX == x
Time Complexity: O(N)
Space Complexity: O(1)
class Solution:
def isPalindrome(self, x: int) -> bool:
if x < 0:
return False
headDivisor = 1
while x // headDivisor >= 10:
headDivisor *= 10
while headDivisor >= 10:
# Cmp head & tail digit
if (x // headDivisor) != (x % 10):
return False
# Moving Head & Tail Digit to Center
x = (x % headDivisor) // 10
headDivisor //= 100
return True
Time Complexity: O(N)
Space Complexity: O(1)