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
相关文章推荐
- 《利用Python 进行数据分析》 - 笔记(2)
- 用python爬虫抓站的一些技巧总结
- Python爬虫模拟登录带验证码网站
- python 爬虫实战--登陆学校教务系统获取成绩信息
- 基础知识(十三)dlib python人脸检测
- 好文收藏(持续更新)
- Learning Spark (Python版) 学习笔记(二)----键值对、数据读取与保存、共享特性
- python获取指定时间差的时间
- python获取指定时间差的时间
- python 中文乱码问题
- Python json模块
- python 图片格式转换产生的锯齿问题
- python入门,自制小爬虫获得百度贴吧内容
- Python为什么这么火?
- 步步学习python之环境安装:Vagrant+Ubuntu+Emacs+Virtualenv+Python3开发环境的搭建(Mac电脑下)3
- ubuntu14中创建python虚拟环境
- 使用spyder编译器单步调试python
- 234. Palindrome Linked List [easy] (Python)
- python 模块
- Python pass 语句