Leetcode: 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.

分析:
第一反应是先翻转再看是否相等。

代码:

class Solution:
    def reverse(self, x: int) -> int:
        result = 0
        if x > 0 :
            while(x):
                result = result * 10 + x % 10 
                x //= 10
               #print("x:", x)
               #print("result:", result)
            if result < -2147483647 or result > 2147483647:
                result = 0
        return result

    def isPalindrome(self, x: int) -> bool:
        if x < 0:
            return False
        y = self.reverse(x)
        if x == y:
            return True
        else:
            return False
Author Rewards

Leave a Reply

Your email address will not be published. Required fields are marked *