题目:(3) Palindrome
问题描述:
Determine whether an integer is a palindrome. Do this without extra space.
判断一个整数是否是回文数,没有额外的空间供你使用。
什么是回文数?
1.负数一定不是回文数
2.0是回文数
3.正反一样的数是回文数,例:123321是回文数,1231不是回文数
方法一:
class Solution:
def isPalindrome(self, x):
"""
:type x: int
:rtype: bool
"""
if x >= 0:
y = str(x)[::-1]
y = int(y)
if y == x:
return True
else:
return False
else:
return False
解题思路:
1.利用题目(2)的翻转整数判断
2.注意负数和0
3.有可能还需要注意是否溢出的可能性,此处不需要。
方法二:
class Solution:
def isPalindrome(self, x):
"""
:type x: int
:rtype: bool
"""
while x < 0:
return False
while x >= 0:
ans = 0
ans = ans*10 + x%10
x /= 10
return ans
if ans == x:
return True
else:
return False
解题思路:
1.利用十进制计数法,翻转整数;
2.利用回文数的特性输出True和False。