9. Palindrome Number [Digital] palindromic

description

Determine whether an integer is a palindrome. An integer is a palindrome when it reads the same backward as forward.

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

Examples of
Here Insert Picture Description
ideas

  • Method 1: put into a string of numbers and then compare - the minimum efficiency
  • Method 2 (appropriate): Negative direct return false, to take positive read from back to front, in turn, take a number, and then compare
  • Method 3 (although O (logn), but taking into account more details) do not worry about the numbers will turn over a range of int: negative direct return to a positive number read from back to front, taking half, then comparing with the previous half

answer

  • python
class Solution:
    def isPalindrome(self, x: int) -> bool:
        '''
        方法1
        s = str(x)
        for i in range(int(len(s)/2)):
            if s[i]!=s[len(s)-1-i]:
                return False
        return True
        '''
        '''
        方法2
        if x<0:
            return False
        xx = x
        num=0
        while x:
        
            num = num*10 + x%10
            x = x//10
        
        return False if xx!=num else True
        '''
        #方法3
        if x<0 or (x!=0 and x%10==0): #小于0的和10的倍数且不为0
            return False
       
        num=0
        while x>num:
            num = num*10 + x%10
            x = x//10
    
        if x==num or x==num//10 :
            return True
        return False


  • c++
class Solution {
public:
    bool isPalindrome(int x) {
        /*
        方法1
        string s = to_string(x);
        int L = s.size();
        for (int i=0; i<=(L-1)/2; i++)
            if (s[i] != s[L-1-i])
                return false;
        return true;
        */
        /*
        方法2
        if (x<0) return false;
        int xx = x;//要修改x
        long num=0;//可能会超过int范围
        while (x)
        {
            num = num*10 + x%10;
            x = x/10;
        }
         return xx==num? true: false;
         */
        //方法3
        if (x<0 || (x!=0 && x%10==0)) return false;
        int num = 0;
        while (x>num)
        {
            num = num*10+x%10;
            x/=10;
        }
        
        return (x==num || x==num/10)? true:false;
    }
};
Published 78 original articles · won praise 7 · views 10000 +

Guess you like

Origin blog.csdn.net/puspos/article/details/102968371