9. Palindrome Number

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?

解法

排除负数,10 的倍数等特殊输入。只需要判断数字的前半部分是否等于后半部分的翻转,例如:

12321 -> 123 // 10 == 12
123321 -> 123 == 123

判断数字翻转一半的方法是翻转后的数字大于等于当前的数字。

class Solution:
    def isPalindrome(self, x: int) -> bool:
        if x < 0 or (x != 0 and x % 10 == 0):
            return False

        res = 0
        while x > res:
            res = res * 10 + x % 10
            x //= 10

        return res // 10 == x or res == x

如果转成字符串的话可以使用判断回文字符串方法来判断,还可以使用双指针的方法。

参考

方法:反转一半数字

Last updated

Was this helpful?