LeetCode 9. Number(回文数)

原题:

IDetermine 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.

My solution

class Solution:
    def isPalindrome(self, x):
        """
        :type x: int
        :rtype: bool
        """
        res_mark = True
        temp_str = str(x)
        for i in range(len(temp_str)):
            if i <= len(temp_str) - i - 1:
                if temp_str[i] == temp_str[len(temp_str) - i - 1]:
                    continue
                else:
                    res_mark = False
                    break
            else:
                break
        if res_mark:
            return True
        else:
            return False

Reference solution

题目分析:这一题怕是目前最简单的啦!之前做过回文子串可比这个难噢,而且反转整数和这题基本没差别。这里小詹提供两种思路解决。

思路一:直接利用反转整数类似的方法进行判断,判断反转前后的结果是否相等即可。

#这个太简单了,就不写注释了,可以自行参考历史纪录(反转整数)
class Solution:
    def isPalindrome(self, x):
        """
        :type x: int
        :rtype: bool
        """
        z = x
        y = 0
        while x > 0:
            y = y * 10 + x % 10
            x //= 10
        return z == y

思路二:第二种就是直接强制将其转换为字符串的形式,再进行判断,主要是考虑到列表的反转操作很容易。

class Solution:
    def isPalindrome(self, x):
        """
        :type x: int
        :rtype: bool
        """
        str_x = str(x)
        str_x_re = list(str_x)[::-1]
        str_x_re = "".join(str_x_re)
        return str_x == str_x_re
#下边给出错误的返回方法,不是字符串,也不存在直接的true or false
#而是直接利用 str_x == str_x_re  返回的bool型参数
        # if str_x == str_x_re:
        #     return true
        #     # result = 'true'
        # else:
        #     # result = 'false'
        #     return false
        # # return result

总结

应该注意的点:

  • 反转整数的求法:
while x > 0:
    y = y * 10 + x % 10
    x //= 10
  • 反转字符串
str_x_re = list(str_x)[::-1]
       str_x_re = "".join(str_x_re)

猜你喜欢

转载自blog.csdn.net/Dby_freedom/article/details/82384146