欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

回文数判断(Leetcode)

程序员文章站 2024-03-22 16:14:04
...

problem address

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.
Follow up:

Coud you solve it without converting the integer to a string?

前面了两种方法是取巧了,另外不用转化成字符串怎么做?
可以将数字每位上取出来然后再进行比较

class Solution:
    def isPalindrome(self, x: int) -> bool:
        # return list(str(x)) == list(reversed(str(x)))
        # return str(x) == str(x)[::-1]
        if x < 0:
            return False
        beg = 0
        s = str(x)
        beg, end = 0, len(s) - 1
        while beg < end:
            if s[beg] == s[end]:
                beg += 1
                end -= 1
            else:
                return False
        return True

class Solution:
    def isPalindrome(self, x: int) -> bool:
        if x < 0:
            return False 
        elif x == 0:
            return True
        l = [] 
        while x != 0:
            l.append(x%10)
            x = x // 10 
        return l == list(reversed(l))