LeetCode Palindrome Number
2015-06-07 19:57
393 查看
题目来源:https://leetcode.com/problems/palindrome-number/
题目要求不能使用额外空间,那就只能使用log10求出数字长度,然后分别从高位和低位开始,依次判断是否想等了。
题目需要注意以下几点:
1. 负数直接返回false;
2. 0应该返回true;
代码如下:
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.
题目要求不能使用额外空间,那就只能使用log10求出数字长度,然后分别从高位和低位开始,依次判断是否想等了。
题目需要注意以下几点:
1. 负数直接返回false;
2. 0应该返回true;
代码如下:
class Solution { public: bool isPalindrome(int x) { if (x < 0) return false; int len = log10(x); for (int i = 0; i < (len / 2 + 1); i++) { if ((x / (int)pow(10, i)) % 10 != (x / (int)pow(10, len - i)) % 10) return false; } return true; } };
相关文章推荐
- LCS最长公共子序列 动态规划方法 递归与非递归算法
- zookeeper应用 - leader选举 锁
- 触屏Tap模拟事件
- Java程序员面试失败的5大原因
- java语言的跨平台原理以及环境的搭建
- python cx_Oracle 模块安装记录
- Java程序员面试失败的5大原因
- java中Hashtable浅析
- 一元多项式的表示及相加 数据结构
- Git diff (---和+++具体解释)
- SSH之Struts2篇
- Deep Learning Papers
- Websocket for Tsung
- 应用高级数据结构优化Redis
- Loaders异步加载数据的方式
- 高考四年后的一次演讲
- Head First---命令模式
- Extjs 防止按钮重复点击插件
- Android开发资源获取国内代理(转载)
- zookeeper应用 - FIFO 队列 分布式队列