从0开始的leetCode:Reverse Integer

本题难度为simple,应该是算法上比较简单(我用的String来reverse),但是细节太多了,主要说说我遇到的错误:

  • ”-“的处理,负号不能reverse
  • 0的处理,0在翻转的时候可能出现在第一位需要舍弃,但是只有0的时候又不能舍弃。
  • 再者是长度,正负数不能超过最大值,如果用string则至少是正数不超过10位,负数不超过11位。

答案:短短几行,就可以解决上述所有问题,精彩。

难理解处:为什么要判断(int)res==res??如何控制超出整数范围的数返回0的?

public int reverse(int x) {
        long res = 0;
        while (x != 0) {
            res *= 10;
            res += x % 10;
            x /= 10;
        }
        return (int)res == res ? (int)res : 0;
    }

解释如下:

Hi, everyone!

Nice solution, but, as many others, I didn't get the line if ((newResult - tail) / 10 != result).

We're interested on what happens when an integer overflows. Well, it is rolled over. Practically speaking, if you would try

    public static void main(String[] args) {
        int rollMeOver= Integer.MAX_VALUE + 1;
        System.out.println(rollMeOver);
    }

 

You will get as an output -2147483648 which represents the lowest value for an integer (Integer.MIN_VALUE).

Thus, in our problem, if newResult is going to overflow we are sure that newResult / 10 != result (this is the reason that @Inception_wzd said that we don't need to subtract the tail first because by / 10 we are already losing the last digit).

By the way, the same thing happens for the underflow.

    public static void main(String[] args) {
        int rollMeOver= Integer.MIN_VALUE - 1;
        System.out.println(rollMeOver);
    }

 

This is going to output the Integer.MAX_VALUE which is 2147483647 .

Hope it helps!

Good luck! :D

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值