判断一个整数(integer)是否是回文,不要使用额外的空间。
一些提示:
负数是否是回文数?(ie,1)
如果您正在考虑将整数转换为字符串,请注意使用额外空间的限制。
您还可以尝试反转整数。但是,如果您已经解决了“反向整数”这个问题,
那么您知道反向整数可能会溢出。你将如何处理这种情况?
有一个更通用的方法来解决这个问题。
方法1:转化字符串,切片反转(不合题意,列出参考)
class Solution(object):
def isPalindrome(self, x):
"""
:type x: int
:rtype: bool
""
def isPalindrome(self, x):
return str(x) == str(x)[::-1]
方法2:既然不能将数字转字符串,那仍然可以考虑生成一个反转整数,
通过比较反转整数和原整数是否相等来判断回文。
class Solution(object):
def isPalindrome(self, x):
"""
:type x: int
:rtype: bool
"""
if x < 0 or (x != 0 and x%10 == 0):
return False
y = 0
temp=x
while (temp!=0):
y = y*10 + temp%10
temp= temp/10
return x == y
因为 Python 语言本身的特性,这里反转整数时不需要考虑溢出,
但不代表如果是C/C++等语言也不需要考虑。 另外,特定于本
问题,溢出与否对结果没有影响。因为原数字是正常无溢出的,
那么如果反转溢出则说明反转后的数字与原数字不相等。
方法3:将数字反转一半,例如123321,比较123和321的翻转,
12321,比较12和321的翻转123整除10的结果,还有以0结尾的
都不是回文数字
class Solution(object):
def isPalindrome(self, x):
"""
:type x: int
:rtype: bool
"""
if x<0 or (x!=0 and x%10==0):
return False
if x==0:
return True
y=0
while(x!=0 and y!=x):
y=x%10+y*10
x=x/10
return x==y
"""
代码运行是正确的,但是提交这个没有考虑到121等情况,
不会存在x==y。
"""
class Solution(object):
def isPalindrome(self, x):
"""
:type x: int
:rtype: bool
"""
if x<0 or (x!=0 and x%10==0):
return False
if x==0:
return True
y=0
while x>y:
y=x%10+y*10
x=x/10
return x==y or y/10==x
方法4:数字分离逐个比较。
class Solution(object):
def isPalindrome(self, x):
"""
:type x: int
:rtype: bool
"""
if x < 0:
return False
digits = 1
while x/digits >= 10:
digits *= 10
while digits > 1:
right = x%10
left = x/digits
if left != right:
return False
x = (x%digits) / 10
digits /= 100
return True