LeetCode刷题:第9题PalindromeNumber

正月十六,这个年算是彻底过完了,也该开始干活了。在LeetCode上做的第二道题,详细内容如下:


**题目要求:**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.


思路分析:题目要求很简单,判断一个integer类型的数是否为回文数,但是要求不允许使用额外的空间,所以我们不可能考虑通过将integer转换成string后再进行convert,也就是问题提示中的第二条内容。再看下官方给的提示第一条,负数不可能是回文数,这里讲的就是一个边界问题,所以代码编写的时候肯定先去除这种边界之外的情况。接着看第三条提示,也就是将我们的integer整个reverse,系统提示我们会出现整数溢出问题,所以这种方法我们也不能再考虑了。

所以综上,我们只能使用数学计算的方法解决本题,而且还不能将我们的目标target整个reverse,所以我们只能考虑将目标target部分reverse,而这个“部分”的量是多少?因为是回文数,所以不难想出这个“部分”的大小就是一半。

那么问题又来了,这个一半的大小如何判断,什么时候我们找到了target的一半的数字?其实也不是很难,举个例子,对于12321来说,我们肯定要先获得个位,也就是12321%10 == 1,然后在将12321/10 = 1232,再将1232%10 =2,将之前的1*10再加上2,以此类推,所以我们通过我们得到的revert与“原数x”(其实并不是实际意义上的原数,而是每步都除以10之后的数)比较,如果“原数x”比revert小的时候,说明我们就已经处理了一半的数字了。


代码实现:

public static boolean isPalindrome(int x){
        if(x<0 || (x%10 == 0 && x!=0))
            return false;
        int revert = 0;
        while(x>revert){
            revert = revert*10+x%10;
            x = x/10;
        }
        if(x == revert || x == revert/10)
            return true;
        return false;
    }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

CliuGeek

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值