Leetcode 回文数

Leetcode 回文数

回文数

判断一个整数是否是回文数。回文数是指正序(从左向右)和倒序(从右向左)读都是一样的整数。

示例 1:

输入: 121
输出: true

示例 2:

输入: -121
输出: false
解释: 从左向右读, 为 -121 。 从右向左读, 为 121- 。因此它不是一个回文数。

示例 3:

输入: 10
输出: false
解释: 从右向左读, 为 01 。因此它不是一个回文数。

进阶: 你能不将整数转为字符串来解决这个问题吗?

解题思路

判断是否负数, 是负数直接返回False
正数的时候, 转化字符串再转为数组,
取数组长度的一半取整, 然后对数组前后各一半对比, 有一个不同则返回False, 否则返回True

Answer

 1#
 2# @lc app=leetcode.cn id=9 lang=python3
 3#
 4# [9] 回文数
 5#
 6
 7# @lc code=start
 8class Solution:
 9    def isPalindrome(self, x: int) -> bool:
10        if x < 0:
11            return False
12        else:
13            ary = list(str(x))
14            lens = len(ary)
15            half = lens // 2
16            for i in range(0,half):
17                if ary[i] != ary[ -1 * (i + 1)]:
18                    return False
19            return True
20
21# @lc code=end

Accepted

11509/11509 cases passed (84 ms)
Your runtime beats 71.7 % of python3 submissions
Your memory usage beats 5.88 % of python3 submissions (13.8 MB)

进阶思考

首先判断负数, 直接返回False
正数的话, 原始x除10取余数赋值给y, x除10商赋值给s
如果s不为0, 则将商s赋值给x, 继续除10, 余数赋值给 y = y*10 + 本次余数, 商继续赋值给s
知道商s为0, 此时判断 y==s 返回判断结果

进阶 Answer

 1#
 2# @lc app=leetcode.cn id=9 lang=python3
 3#
 4# [9] 回文数
 5#
 6
 7# @lc code=start
 8class Solution:
 9    def isPalindrome(self, x: int) -> bool:
10        if x < 0:
11            return False
12        k = x
13        y = 0
14        while True:
15            y = x % 10 if y == 0 else y * 10 + x % 10
16            s = x // 10
17            if not s:
18                break
19            x = s
20        return y == k
21# @lc code=end
11509/11509 cases passed (88 ms)
Your runtime beats 60.61 % of python3 submissions
Your memory usage beats 5.88 % of python3 submissions (13.7 MB)