【力扣算法题-Python】第9题、回文数

【力扣算法题-Python】第9题、回文数

  • 题目
  • 思路
  • 解题
    • 初级,字符串方式
    • 进阶,数字的方式

题目

题目:回文数。

难度:简单。

给你一个整数 x ,如果 x 是一个回文整数,返回 true ;否则,返回 false

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

  • 例如,121 是回文,而 123 不是。

示例 1:

输入:x = 121
输出:true

示例 2:

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

示例 3:

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

提示:

  • -231 <= x <= 231 - 1

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

Related Topics

数学

2393

0

思路

题目中说:

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

说明可以转字符串的方式来做。

回文数是从左到右读和从右到左读都是一样的,所以负数不是回文数,能被10整除的数也不是回文数,小于10的非负数是回文数,并且如果将数据转换成字符串,那么字符串反转后和原字符串相同。

解题

初级,字符串方式

在这种方式中,将数字转成字符串,然后将字符串反转,如果反转后和原字符串相同,则是回文数。

代码如下:

class Solution(object):
    def isPalindrome(self, x):
        """
        :type x: int
        :rtype: bool
        """
        if x in range(10):
            return True
        
        if x < 0 or x % 10 == 0:
            return False

        return str(x) == "".join(reversed(str(x)))

或者:

class Solution(object):
    def isPalindrome(self, x):
        """
        :type x: int
        :rtype: bool
        """
        if x in range(10):
            return True
        
        if x < 0 or x % 10 == 0:
            return False

        return str(x) == str(x)[::-1]

提交执行,效果并不理想,耗时比较长。

> 2023/02/05 16:41:26	
Success:
	Runtime:64 ms, faster than 61.88% of Python3 online submissions.
	Memory Usage:14.8 MB, less than 86.77% of Python3 online submissions.

【力扣算法题-Python】第9题、回文数_第1张图片

反复提交运行,可以得到一个比较快的运行时间,这个时间应该算是很快了,超过99.99%的提交记录,只是空间还是不小。

> 2023/02/06 18:18:58	
Success:
	Runtime:32 ms, faster than 99.99% of Python3 online submissions.
	Memory Usage:14.9 MB, less than 70.46% of Python3 online submissions.

【力扣算法题-Python】第9题、回文数_第2张图片

进阶,数字的方式

按照题目要求,不将整数转为字符串来解决这个问题。

直接使用数值来进行解决。

思路是数字的低位逐渐升高位,高位逐渐降为低位,直到数值反转完成。

代码如下:

class Solution(object):
    def isPalindrome(self, x):
        """
        :type x: int
        :rtype: bool
        """
        if x in range(10):
            return True

        if x < 0 or x % 10 == 0:
            return False

        x1 = x
        x2 = 0
        while x1 != 0:
            x2 = x2 * 10 + x1 % 10
            x1 //= 10
        return x2 == x

提交执行,效果一般。

> 2023/02/06 18:46:11	
Success:
	Runtime:68 ms, faster than 45.74% of Python3 online submissions.
	Memory Usage:14.9 MB, less than 70.46% of Python3 online submissions.

【力扣算法题-Python】第9题、回文数_第3张图片

你可能感兴趣的:(#,力扣,leetcode,算法,python,力扣)