No.009 Palindrome Number
2016-07-26 19:26
183 查看
9. Palindrome Number
Total Accepted: 136330Total Submissions: 418995
Difficulty: Easy
Determine whether an integer is a palindrome. Do this without extra space.
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.
思路:
本题解题很简单,首先判断负数和0,然后我们计算得到最大基数,如果x为一个两位数,则基数base=100,三位数则为1000等,然后我们每次分别取这个数的最高位和最低位进行比较,如果不相等,则直接返回false,相等则去掉最左边和最右边的数后进行下一轮比较。代码如下:
public boolean isPalindrome(int x) { if(x < 0){ return false ; } if(x == 0 ){ return true ; } int base = 1 ; while(x/base >= 10){ base *= 10 ; } while(x != 0){ int leftDigit = x/base ; int rightDigit = x%10 ; if(leftDigit != rightDigit){ return false ; } x = x%base/10 ; base /= 100 ; } return true ; }
相关文章推荐
- CentOS从入门到精通系列之PPTP
- Material Design的使用
- Web网站发布权限问题
- Linux 下的Tmux的使用记录
- React-Native for iOS
- Dynamics CRM 2016 安装
- POJ 1905 Expanding Rods(二分)
- object类中相关方法
- 一个小白的内心自白
- HDU4907Task schedule二分
- 汉诺塔(一)
- Class.getResource和ClassLoader.getResource的路径区别
- interface 接口的特点
- 补充——理解$watch ,$apply 和 $digest --- 理解数据绑定过程
- cocos2dx-lua ios系统访问系统相册
- 【深入理解JVM】内存模型
- 在CentOS 7系统上架设DHCP服务
- 尼克的任务(线性DP)
- 系统基础之获取命令使用帮助
- 数组去重 算法实现