Determine whether an integer is a palindrome. An integer is a palindrome when it reads the same backward as forward.
Example 1: Input: 121 Output: true
Example 2: Input: -121 Output: false Explanation: From left to right, it reads -121. From right to left, it becomes 121-. Therefore it is not a palindrome.
Example 3: Input: 10 Output: false Explanation: Reads 01 from right to left. Therefore it is not a palindrome.
Follow up: Coud you solve it without converting the integer to a string?
思路
这道题最简单的解决办法是将数字转换成字符串,从头和尾向中间进行遍历。可以得出结果。但是在题中给出了可不可以不适用转化字符的办法来解决。这里我想到了使用辅助空间来解决。 申请一个堆和队列。然后依此将数字加入其中。然后再逐个对比数字是否相等。相等则时回文。时间复杂度为O(log 10 n), 空间复杂度为O(n).
图示步骤
实现代码
class Solution(object):
def isPalindrome(self, x):
"""
:type x: int
:rtype: bool
"""
if x < : # 如果数字小于0,直接返回
return False
tem1, tem2 = [], [] # 设置两个辅助列表来模拟栈和队列。
while x: # 堆数字进行遍历
tem = x %
tem1.append(tem)
tem2.append(tem)
x //= 10
i, end = , len(tem1)-1
while i < len(tem1) and end >= : # 队列和栈来依此访问。
if tem1[i] != tem2[end]:
return False # 有一个不相等直接返回。
i +=
end -=
return True