题目描述
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.
题目翻译
确定整数是否是回文。当一个整数向后读取与向前读取相同的内容时,它就是一个回文。
思路方法
- 负数都不是回文数
- 不能通过将数字转为字符串来判断回文,因为使用了额外的空间(即只能使用空间复杂度 O(1) 的方法)
- 注意整数溢出问题
代码实现
- 思路一
因为 Python 语言本身的特性,这里反转整数时不需要考虑溢出,但不代表如果是C/C++等语言也不需要考虑。
另外,特定于本问题,溢出与否对结果没有影响。因为原数字是正常无溢出的,那么如果反转溢出则说明反转后的数字与原数字不相等。
def isPalindrome(self, x):
"""
:type x: int
:rtype: bool
"""
if x < 0:# 输入数值为负数
return False
tmp = x # 将输入数值赋值给临时变量
# 将原数字进行反转
y = 0
while tmp:
y = y*10 + tmp%10
tmp = tmp/10
return y == x
- 思路二:
对思路一进行优化,将原数字反转一半就可以判断是否是回文。另外,以0结尾的非零数都不是回文。
def isPalindrome(self, x):
"""
:type x: int
:rtype: bool
"""
if x < 0 or (x != 0 and x%10 == 0):# 以0结尾或者负数不是回文
return False
#将原数字进行反转一半
y = 0
while x > y:
y = y*10 + x%10
x = x/10
return x == y or y/10 == x
总结
- 对于一个整数反转,需要考虑溢出问题,其数值范围是 [−2^31,2 ^31 − 1]。
- 需要掌握给定一个整数如何分离各个数字:
方法一:数字除10求出余数 ,那个余数就是个位数,然后求商代表没有个位数的数,然后重复做重复性操作。
方法二:将正整数转化成字符串,再进行提取各个字符。