【id】#9
【title】 Palindrome Number
【description】
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.
Example 3:
Input: 10
Output: false
Explanation: Reads 01 from right to left. Therefore it is not a palindrome.
【idea】
直接运用字符串的反转。虽然不符合题目要求~~
【code】
class Solution(object):
def isPalindrome(self, x):
"""
:type x: int
:rtype: bool
"""
return True if str(x) == str(x)[::-1] else False
【idea2】
首先判断负数(带有-)和除0本身外以0结尾的数为False;然后反转数字的一半,如果反转后二者相同则为回文数字,比如1221,反转一般为12,12相同。
判断数字的中间节点方法为,因为我们是x%10得到pop的数字,此时原数字为x/10,反转后的数字为rev*10,所以只要剩余的原数字不大于反转后的数字时,即到达了数字的中间节点。
【code】
# revert half of the number
class Solution(object):
def isPalindrome(self, x):
"""
:type x: int
:rtype: bool
"""
if x <0 or (x%10==0 and x != 0): return False
# 当剩余的原数字小于反转生成的数字时,说明已经到达了数字中间
revert_num = 0
while x > revert_num:
revert_num = 10* revert_num + x % 10
x //= 10
# print(revert_num,x)
return revert_num == x or revert_num//10 ==x
s = 121
Solution().isPalindrome(s)