LeetCode_9_ digit palindrome

The number of palindromes (LeetCode 9)

1. Topic

Determine whether an integer is a palindrome. Palindrome correct order (from left to right) and reverse (right to left) reading is the same integer.

Example 1:

输入: 121
输出: true

Example 2:

输入: -121
输出: false
解释: 从左向右读, 为 -121 。 从右向左读, 为 121- 。因此它不是一个回文数。

Example 3:

输入: 10
输出: false
解释: 从右向左读, 为 01 。因此它不是一个回文数。

Advanced:

You can not be an integer into a string to solve this problem?

2. Analysis

Integer Retrograde

3. Code

Do not write their own reverse

    def isPalindrome(self, x: 'int') -> 'bool':
        x = str(x)
        new_x = x[::-1]
        if new_x == x: 
                return True
        return False

Write your own judgment reversed

    def isPalindrome(self, x: 'int') -> 'bool':
        x = str(x)
        return self.func(x)
    def func(self, x):
        l, r =0, len(x)-1
        while l<r:
            if x[l] != x[r]:
                return False
            l += 1
            r -= 1
        return True

Integer Retrograde

    def isPalindrome(self, x: 'int') -> 'bool':
        # 如果负数,不是回文数;如果个位数是0(除0这种特殊情况),不是回文数
        if x<0 or (x!=0 and x%10==0):
            return False
        y = x
        n = 0
        # 逆置 整数
        while x:
            n = n * 10 + x % 10
            x = x//10
        return n==y

Half the number of reversal

   # 反转一半数
    def isPalindrome(self, x: 'int') -> 'bool':
        if x<0 or (x!=0 and x%10==0):
            return False
        right_rev = 0
        while x > right_rev:
            right_rev = right_rev*10 + x%10
            x = x//10
       #    奇偶情况都考虑
        return x==right_rev or x==right_rev//10

Guess you like

Origin www.cnblogs.com/biggw/p/11334502.html