Leetcode 9. Palindrome Number
2016-04-23 10:38
344 查看
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.
大致题意:判断一个整形是否是回文整形,不能使用额外空间。
方法1:先逆置这个整数,比较他们是否相等(多用的了一个int额外空间但也能通过)
代码如下:
代码如下:
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.
大致题意:判断一个整形是否是回文整形,不能使用额外空间。
方法1:先逆置这个整数,比较他们是否相等(多用的了一个int额外空间但也能通过)
代码如下:
class Solution { public: bool isPalindrome(int x) { if(x<0) return false; int i=x,rev=0; while(i){ if(rev>INT_MAX/10||rev<INT_MIN/10) return false; rev=10*rev+i%10; i/=10; } if(rev==x) return true; else return false; } };方法2:比较前后两个位是否相等,判断后去掉头尾两个位。
代码如下:
class Solution { public: bool isPalindrome(int x) { if(x<0) return false; int div=1; while(x/div>=10) div*=10; while(x!=0){//注意终止条件 int left=x/div; int right=x%10; if(left!=right) return false; x=(x%div)/10; div/=100; } return true; } };方法2参考来源:http://blog.csdn.net/feliciafay/article/details/17134663
相关文章推荐
- 使用C++实现JNI接口需要注意的事项
- 关于指针的一些事情
- c++ primer 第五版 笔记前言
- share_ptr的几个注意点
- Lua中调用C++函数示例
- Lua教程(一):在C++中嵌入Lua脚本
- Lua教程(二):C++和Lua相互传递数据示例
- C++联合体转换成C#结构的实现方法
- C++高级程序员成长之路
- C++编写简单的打靶游戏
- C++ 自定义控件的移植问题
- C++变位词问题分析
- C/C++数据对齐详细解析
- C++基于栈实现铁轨问题
- C++中引用的使用总结
- 使用Lua来扩展C++程序的方法
- C++中调用Lua函数实例
- Lua和C++的通信流程代码实例
- C与C++之间相互调用实例方法讲解
- 解析C++中派生的概念以及派生类成员的访问属性