题目描述
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.
Follow up:
Coud you solve it without converting the integer to a string?
解析
不转化成字符串,判断数字是否为回文数 。
对于较大数字,转换成字符串判断方便。对于题目中这种整型数字,按位判断数字即可。
class Solution {
public:
bool isPalindrome(int x) {
if(x<0) return false;
else if(x==0) return true;
else
{
int ch[30];
int t=0;
while(x)
{
ch[t++]=x%10;
x/=10;
}
for(int i=0;i<t;i++)
{
if(ch[i]!=ch[t-1-i]) return false;
}
return true;
}
}
};
(其实翻转数字的一半即可)
最近在学习数据结构,课本上有习题要求用栈和队列实现(利用了栈后进先出和队列先进先出的性质),于是也写了个:
class Solution {
public:
bool isPalindrome(int x) {
stack <int> t;
queue <int> q;
if(x<0) return false;
else if(x==0) return true;
else
{
while(x)
{
t.push(x%10);
q.push(x%10);
x/=10;
}
while(!t.empty())
{
if(t.top()!=q.front()) return false;
else
{
t.pop();
q.pop();
}
}
return true;
}
}
};
从运行结果来看,用栈和队列既费时间又费内存。