您的位置:首页 > 其它

LeetCode 之 Palindrome Number

2013-11-12 17:47 369 查看
原题:

Determine whether an integer is a palindrome. Do this without extra space.

click to show spoilers.

Some hints:
Could negative integers be palindromes? (ie, -1)
If you are thinking of converting the integer to string, note the restriction of using extra space.
You could also try reversing an integer. However, if you have solved the problem "Reverse Integer", you know that the reversed integer
might overflow. How would you handle such case?
There is a more generic way of solving this problem.
这个题其实就是判断一个数是否是对称的,原题中的hint提到的overflow是指如果一个数反转过来可能会溢出,

,会有人用这么笨的方法么,反转过来再判断是否相等???学渣都没想到这么渣的算法。。。。
好了,看到网上好多人用的都是一种方法,判断首位的数字是否相等,这个方法需要先计算这个数的最高位,用最笨的方法,乘10上去,最后除一下。。。然后在把这个数的首尾去掉,继续判断。。。。
说下我用的方法,就是用栈么。。
1 如果栈空,就把x%10入栈
2 栈不空,比较x%10和栈顶,不相等则入栈,相等则pop
3 如果该数为偶数,则用1,2即可,如果为基数,如101,则需要对最中间的数进行处理,我是先算出数的位数,然后当循环进行到中间时,直接再/10一次即可跳过对中间数的判断
4 栈为空返回true , 最后388ms过的
代码如下:

class Solution {

public:

bool isPalindrome(int x) {
// IMPORTANT: Please reset any member data you declared, as
// the same Solution instance will be reused for each test case.

if(x<0) return false;
if(x>=0&&x<10) return true;

int n = log10(x) + 1;
int i = 1;
stack<int> s;
//每次对x的余数进行考虑,用i记录是否到了中间
for(; x!=0; x=x/10,i++){

int current = x%10;
if(s.empty()){
//栈为空,则入栈
s.push(current);
}
else {
//栈不为空
if(s.top()!=current){
//栈顶不等于余数,则入栈
s.push(current);
}
else{
//等于则出栈
s.pop();
}
}
//下一次进行的就是中间数,直接/10跳过
if(n%2!=0 && i==n/2){
x=x/10;
}
}
//栈不为空则返回true
return s.empty()?true:false;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: