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过的
代码如下:
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; } };
相关文章推荐
- unbuntu下splint的使用与配置
- Android Drawable文件分类及内存问题
- C指针动态内容分配
- 实战ios Plist 读 写操作及修改 删除 排序
- 1009. Product of Polynomials (25)
- eclipse离线安装插件
- 小笔记---从asset中取出apk,然后安装。
- 算法的时间性能分析
- Webservice测试工具
- QT中添加MFC库,QT中添加windows函数库
- 双层汉诺塔、八皇后等问题
- 上海Oracle用户组我的页面
- 13个mysql数据库的实用SQL小技巧
- test
- Coding templates and formatters
- swift mul node install
- iphone相对精准nstimer实现
- 仿12306客户端
- JavaScript实现url地址自动检测并添加URL链接示例代码
- 海盗分金