leetcode9-- Palindrome Number

leetcode9-- Palindrome Number

题目



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

解答 如果可以转成str的话,那就比较容易

class Solution:
    def isPalindrome(self, x: int) -> bool:
        if x<0:
            return False
        
        x = str(x)
        if len(x)==1:
            return True
        
        left, right = 0, len(x)-1
        while left<=right:
            if x[left] != x[right]:
                return False
            left += 1
            right -= 1
        
        return True

如果不能转成str的话,就一边求出每一位上的数字,一边算反过来之后的数字

class Solution:
    def isPalindrome(self, x: int) -> bool:
        if x<0:
            return False
        num = x
        ret = 0
        
        while num != 0:
            ret = ret*10+num%10
            num //=10
            
        return ret==x

打赏,谢谢~~

取消

感谢您的支持,我会继续努力的!

扫码支持
扫码打赏,多谢支持~

打开微信扫一扫,即可进行扫码打赏哦