LeetCode 9 Palindrome Number

148 阅读1分钟

LeetCode 9 Palindrome Number

思路

  1. 将每一位取出来,放入stack,此时个位在栈底,最高位在栈顶。将其中一半放入另一个栈,然后检查两个栈的栈顶元素是否相同。

  2. 第一种方法显然效率不够高。第二种思路与第一种相似,提高效率的部分在于循环条件,减少了不少计算量。

代码

方法1

class Solution {
public:
    bool isPalindrome(int x) {
        if (x < 0  || (x != 0 && x % 10 == 0)) return false;
        
        stack<int> stk1, stk2;
        
        while (x) {
            stk1.push(x%10);
            x /= 10;
        }
        
        int length = stk1.size();
        int popCount = length / 2;
        
        for (int i = 0; i < popCount; ++i) {
            stk2.push(stk1.top());
            stk1.pop();
        }
        
        if (length % 2) stk1.pop();
        
        while (!stk1.empty()) {
            if (stk1.top() != stk2.top())
                return false;
            stk1.pop();
            stk2.pop();
        }
        
        return true;
    }
};

方法2

class Solution {
public:
    bool isPalindrome(int x) {
        if (x < 0 || (x != 0 && x%10 == 0)) return false;
        int sum = 0;
        while (x > sum) {
            sum = sum * 10 + x % 10;
            x /= 10;
        }
        
        return (x == sum) || (x == sum/10);
    }
};