[LeetCode] Palindrome_Number_20190115
题目:
Leetcode
等级easy
:
Determine whether an integer is a palindrome. An integer is a palindrome when it reads the same backward as forward.
Follow up:
Coud you solve it without converting the integer to a string?
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.
分析及思路:
这是一个经典的题目了,也十分简单,特别是在有之前翻转数字的经验上。回文数,不管前后如何翻转是不会发生改变的,也就是说翻转前后值一致,而且负数不可能是回文,只有一位数则一定是回文。基于以上思路想到方法有两种:一种通过字符串实现翻转对比,一种通过数学计算翻转对比
实现:
字符串翻转对比:
class Solution:
def isPalindrome(self, x):
"""
:type x: int
:rtype: bool
"""
if x < 0: # 负数
return False
if x < 10: # 仅个位数
return True
return str(x) == str(x)[::-1] # 对比及翻转
数学计算方法:
class Solution:
def isPalindrome(self, x):
if x < 0:
return False
if x < 10:
return True
temp = x
cmp = 0
while temp > 0:
cmp = cmp*10 + temp%10 # 翻转(翻转数字同样的方法)
temp = temp//10
return x==cmp
结果:
关于运行时间这个问题,仅作结果展示,做一个参考依据(误差挺大的),因为每次提交都不一样,而且这次查看运行时间靠前的,用的方法也不外乎是这两种,但是我就是慢了一倍多,哈哈。
分析:
前面的负数及个位数判断主要减少运行时间的目的,在字符串解法中是可以直接去掉的,也就是如果用字符串解法是可以一行代码搞定的,比较容易,这可能也是题目中为什么说不用字符串解的原因。数学解法中也可以去掉优化,需要做少量修改。此外数学方法中的数字翻转,也可直接用在之前的翻转数字一题中,这也算是学习的不断积累吧。