palindrome number(回文数)

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.

 

判断一个整数是否是回文数,要求是不使用额外空间。

回文数是指正着过去和反着回来都是一样的,如1221,12121.

本来可以转成字符串,然后从前后开始比较即可,但是题目说不能使用额外空间,所以这一条不成立。

可以旋转这个整数,旋转回来的数和这个数相等就是回文数。考虑到旋转会导致溢出,这时返回false即可,因为x是int型,如果是回文数,它也是x,不可能溢出。

还可以简洁一点,因为是前半部分和后半部分的旋转是一样的,所以可以旋转一半,这时比较。当然,这时要注意x由奇数个数字组成时和偶数个数字组成的情况,

 

class Solution {
    public boolean isPalindrome(int x) {
        if(x<0||(x!=0&&x%10==0))
            return false;
        int res=0;
     /*
    //全部旋转
int a=x; while(x>0){ int tail=x%10; int newRes=res*10+tail; if((newRes-tail)/10!=res) return false; res=newRes; x=x/10; } return a==res; */ //旋转整数,只要旋转一半就行了,旋转一半就不会出现溢出问题 while(x>res){ res=res*10+x%10; x=x/10; } return x==res||res/10==x; //分别考虑x是偶数个数字组成,和x是奇数个数字组成 } }

 

 

转载于:https://www.cnblogs.com/xiaolovewei/p/8058302.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值