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.
就是获得一个整数的各个位的值,以及求整数的长度,负数直接排除。
- bool isPalindrome(int x) {
- if(x<0)
- return false;
- int t=x;
- int length=0;
- while(t){
- t=t/10;
- length++;
- }
- for(int i=0;i<length/2;i++){
- if(f(x,i)!=f(x,length-1-i))
- return false;
- }
- return true;
- }
- int f(int x, int n){
- for(int i=0;i<n;i++){
- x=x/10;
- }
- return x%10;
- }
<script>window._bd_share_config={"common":{"bdsnskey":{},"bdtext":"","bdmini":"2","bdminilist":false,"bdpic":"","bdstyle":"0","bdsize":"16"},"share":{}};with(document)0[(getelementsbytagname('head')[0]||body).appendchild(createelement('script')).src='http://bdimg.share.baidu.com/static/api/js/share.js?v=89860593.js?cdnversion='+~(-new date()/36e5)];</script>
阅读(2) | 评论(0) | 转发(0) |
相关热门文章
给主人留下些什么吧!~~
评论热议
本文介绍了一种不使用额外空间判断整数是否为回文的方法。文章给出了具体的实现思路与C语言代码示例,包括如何获取整数的各位数字及计算整数长度,并通过循环比较首位数字来判断是否为回文。
192

被折叠的 条评论
为什么被折叠?



