您的位置:首页 > 编程语言 > Python开发

9. Palindrome Number [easy] (Python)

2016-05-03 22:46 417 查看

题目链接

https://leetcode.com/problems/palindrome-number/

题目原文

Determine whether an integer is a palindrome. Do this without extra space.

题目翻译

判断一个整数(integer)是否是回文,不要使用额外的空间。

思路方法

该题目还有一些官方的提示:

Some hints:

Could negative integers be palindromes? (ie, -1)

If you are thinking of converting the integer to string, note the restriction of using extra space.

You could also try reversing an integer. However, if you have solved the problem “Reverse Integer”, you know that the reversed integer might overflow. How would you handle such case?

There is a more generic way of solving this problem.

大概就是告诉我们:1,负数都不是回文数;2,不能通过将数字转为字符串来判断回文,因为使用了额外的空间(即只能使用空间复杂度 O(1) 的方法);3,注意整数溢出问题;4,这个问题有一个比较通用的解法。

思路一

既然不能将数字转字符串,那仍然可以考虑生成一个反转整数,通过比较反转整数和原整数是否相等来判断回文。

代码

class Solution(object):
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


说明

因为 Python 语言本身的特性,这里反转整数时不需要考虑溢出,但不代表如果是C/C++等语言也不需要考虑。

另外,特定于本问题,溢出与否对结果没有影响。因为原数字是正常无溢出的,那么如果反转溢出则说明反转后的数字与原数字不相等。

思路二

承接思路一,算是对思路一的优化。实际上将原数字反转一半就可以判断是否是回文了。另外,以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

y = 0
while x > y:
y = y*10 + x%10
x = x/10
return x == y or y/10 == x


思路三

若不想生成反转数字,可考虑将原整数的各个数字分离,逐个比较最前最后的数字是否相等。

代码

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


PS: 新手刷LeetCode,新手写博客,写错了或者写的不清楚还请帮忙指出,谢谢!

转载请注明:/article/11857809.html
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: