一、描述
Palindrome NumberEasy13161250FavoriteShareDetermine 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.
二、思路分析
首先,我们需要知道负数是没有回文数一说的。
其次,根据提示,思路1:将整形数字转化为字符串来制作。因为回文数是关于中间位置对称的,转化后根据数组下标,来进行首尾判断等操作即可(根据奇偶分为两种情况,奇数的中位数不用进行判断,且每种情况中,要判等的首位两个 数下标和为串长lenth - 1)。
思路2:将整形数字反转后与原数字判等即可
我选择的是思路1,因为要考虑到不用额外空间的问题,类型转化过程中可能会有空间的浮动变化,但应该没有思路2直接开辟新空间对空间的需求 那么多。
三、Python代码
class Solution(object):
def isPalindrome(self, x):
“”"
:type x: int
:rtype: bool
“”"
#我们要知道负数不是回文数
if x < 0:
return False#转化为字符串,用下标来判断 x = str(x) lenth = len(x) #用&操作来判定是奇数还是偶数,注意下标的匹配问题(每一对收尾判断相同的两个数的下标和恰为lenth-1)。 if lenth & 1 == 0: for i in range(0, lenth / 2): if x[i] != x[lenth - i - 1]: return False else: for i in range(0, (lenth + 1) / 2): if x[i] != x[lenth - i - 1]: return False return True