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

这次找了个简单题目找找自信:)不过我发现我还是太年轻了,程序仅仅可以运行是完全不够的。贴一下第一次代码,还是比较丑陋的,运行速度也比较慢(39%):

class Solution {
public:
    bool isPalindrome(int x) {
        
        if(x<0) return false;
        if(x==0) return true;
        
        vector<int> s;
        
        while(x>0)
        {
            int res =x%10;
            x=x/10;
            s.push_back(res);
        }
        
        
        
        bool isPalindrome = true;
        for(int i=0;i<s.size()/2;i++)
        {
            //int start = i;
            int end   = s.size() - i - 1;
            
            if(s[i] != s[end])
            {
                isPalindrome = false;
                break;
            }
        }
        
        return isPalindrome;
        
    }
};

后来忽然回想起来如果逆转数与原数相等应该也可以,但是忘了数值越界这个大坑,作弊式的用了long long int,然而也并没有多快(56%)

class Solution {
public:
    bool isPalindrome(int x) {
        
        if(x<0) return false;
        if(x==0) return true;
        
        long long int reverse = 0;
        int temp = x;
        while(temp>0)
        {
            int res = temp%10;
            reverse = 10*reverse  + res;
            temp=temp/10;
        }
        cout<<reverse;
        bool isPalindrome = (reverse == x)? true:false;
        
        return isPalindrome;
        
    }
};

又参照了大神的deque法:),但是速度也只是56%左右,不过思路比较新奇和谐

class Solution {
public:
     bool isPalindrome(int x) {
         if (x < 0)
             return false;
         
         deque <int> dq;
        
         while (x > 0)
         {
             dq.push_back(x % 10);
             x /= 10;
         }
        
         while (!dq.empty())
         {
             if (dq.front() != dq.back())
                 return false;
             dq.pop_front();
             if (dq.size() <= 1)
                 return true;
             dq.pop_back();
             if (dq.size() <= 1)
                 return true;
         }
        return true;
    }

};
posted @ 2019-07-12 06:13  孙小鸟  阅读(106)  评论(0编辑  收藏  举报