LeetCode#9 - 回文数
题目描述
代码实现
// 这是我想到的最简单的方法,利用栈和队列特性,先进先出和先进后出相反,然后再弹出比较时间复杂度是O(n),空间复杂度O(n)
class Solution
{
public:
bool isPalindrome(int x)
{
if (x >= pow(2, 31) - 1 || x <= -pow(2, 31))
return false;
if (x < 0)
return false;
queue<int> q;
stack<int> s;
while (x)
{
q.push(x % 10);
s.push(x % 10);
x /= 10;
}
while (!q.empty() && !s.empty())
{
if (q.front() != s.top())
return false;
q.pop();
s.pop();
}
return true;
}
};
// leetcode官方解法:将原始数字一半反转,与另一半比较
class Solution
{
public:
bool isPalindrome(int x)
{
// 负数不是回文,非零的个位数是0的不是回文
if (x < 0 || (x % 10 == 0 && x != 0))
{
return false;
}
int revertedNumber = 0;
while (x > revertedNumber)
{
revertedNumber = revertedNumber * 10 + x % 10;
x /= 10;
}
return x == revertedNumber || x == revertedNumber / 10;
// 第一种情况是偶位数,第二种情况是奇位数,除以10是将中间位丢掉。
}
};
题目链接:回文数