解法:
(1)將數字存入字符串,用兩個指針判斷迴文字符串。
(2)翻轉字符串。但翻轉後的字符串可能會溢出,而對於溢出,各種語言的處理方式不同。
(3)動態規劃法。循環對比數字兩端,若兩端相等,敲除兩端數字並進入下一次循環;若兩端不等,返回False。
Python源碼:
Runtime: 56 ms, faster than 49.68% of Python online submissions for Palindrome Number.
Memory Usage: 11.7 MB, less than 77.11% of Python online submissions for Palindrome Number.
class Solution(object):
def isPalindrome(self, x):
"""
:type x: int
:rtype: bool
"""
if x < 0:
return False
div = 1
while x // div >= 10:
div *= 10
while x != 0:
l = x // div
r = x % 10
if l != r:
return False
x = (x % div) // 10
div = div // 100
return True
我的心路:
沒能實現出推薦解法中的動態規劃法。bug點在於判斷了位數。
Runtime: 44 ms, faster than 83.74% of Python online submissions for Palindrome Number.
Memory Usage: 11.8 MB, less than 37.35% of Python online submissions for Palindrome Number.
class Solution(object):
def isPalindrome(self, x):
"""
:type x: int
:rtype: bool
"""
if x < 0:
return False
y = 0
tmp = x
while tmp > 0:
y = 10 * y + tmp % 10
tmp = tmp // 10
return y == x
六個月前:
Runtime: 64 ms, faster than 28.57% of Python online submissions for Palindrome Number.
Memory Usage: 11.7 MB, less than 61.45% of Python online submissions for Palindrome Number.
class Solution(object):
def isPalindrome(self, x):
"""
:type x: int
:rtype: bool
"""
if x < 0:
return False
p, res = x, 0
while p:
res = res * 10 + p % 10
p /= 10
return res == x