class Solution:
# time O(N) space O(N)
# main idea: string the number and compare from both end ; edge case: num <0 false
def isPalindrome(self, x: int) -> bool:
if x < 0:
return False
s = str(x)
l = 0
r = len(s)-1
while l < r:
if s[l] != s[r]:
return False
l += 1
r -= 1
return True
follow up
class Solution:
# time O(lg(N)) spaceO(1)
def isPalindrome(self, x: int) -> bool:
if x < 0:
return False
def reverse(x):
rev = 0
while x != 0:
pop = x%10
x //= 10
# be aware of overflow
rev = rev*10 + pop
return rev
rev = reverse(x)
return rev == x
optimize
class Solution:
# timeO(lgN) space O(1)
# main idea: haf reverse stop point is when x <= reversed bottom half number
def isPalindrome(self, x: int) -> bool:
#edge case: negtive number and lowest digit numbe is 0
if x < 0 or (x>0 and x%10==0):
return False
rev = 0
while x > rev:
rev = x %10 + rev*10
x//=10
return x == rev or x == rev//10 # odd and even number cases
solution2
class Solution:
# main idea: count digits in number
def isPalindrome(self, x: int) -> bool:
#edge case: negtive number and num == 0
if x < 0:
return False
if x == 0:
return True
digits = math.floor(math.log(x,10) +1)
rev = 0
pop = 0
for i in range(digits//2):
pop = x % 10
rev = pop+ rev*10
x //= 10
if digits%2 ==0 and x ==rev :
return True
if digits%2 != 0 and x//10 ==rev:
return True
return False