题目说明
Determine whether an integer is a palindrome. An integer is a palindrome when it reads the same backward as forward.
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.
代码部分1
class Solution:
def isPalindrome(self, x: 'int') -> 'bool':
out = False
if x < 0:
return out
xrev = str(x)
rev = xrev[::-1]
if xrev == rev:
out = True
return out
Runtime: 240 ms, faster than 86.76% of Python3 online submissions for Palindrome Number.
Memory Usage: 12.7 MB, less than 89.14% of Python3 online submissions for Palindrome Number.
后续在想不可能啊,题目怎么会这个简单
emmm果然有后续
Coud you solve it without converting the integer to a string?
代码部分2
class Solution:
def isPalindrome(self, x: 'int') -> 'bool':
if x < 0:
return False
ranger = 1
while x / ranger >= 10:
ranger *= 10
while x:
left = x // ranger
right = x % 10
if left != right:
return False
x = (x % ranger) // 10
ranger //= 100
return True
Runtime: 248 ms, faster than 78.29% of Python3 online submissions for Palindrome Number.
Memory Usage: 13.5 MB, less than 5.03% of Python3 online submissions for Palindrome Number.
思路解析:
ranger用于寻找最高位:
while x:
left代表此时左边最高位
right代表此时右边最低位
比较left与right:若成功 则继续比较接下来的位置,否则返回false
x对ranger取余(去除最高位);对10向下取整(去除最低位)
ranger降两位
循环,比较次高位与次低位