[Leetcode]Reverse Integer

来源:互联网 发布:350淘宝模板破解 编辑:程序博客网 时间:2024/06/05 06:36

Reverse digits of an integer.

Example1: x = 123, return 321
Example2: x = -123, return -321

click to show spoilers.

Have you thought about this?

Here are some good questions to ask before coding. Bonus points for you if you have already thought through this!

If the integer's last digit is 0, what should the output be? ie, cases such as 10, 100.

Did you notice that the reversed integer might overflow? Assume the input is a 32-bit integer, then the reverse of 1000000003 overflows. How should you handle such cases?

For the purpose of this problem, assume that your function returns 0 when the reversed integer overflows.

Update (2014-11-10):

Test cases had been added to test the overflow behavior.

这道题11月10号有一个更新,加上了反转会溢出的test case。因此要把这一部分数找出来,然后喀嚓掉,返回0。

这里先上没更新前的AC代码,供大家先熟悉思路。

class Solution {public:    int reverse(int x) {        int flag = (x > 0) ? 1:-1;        int y =abs(x);        int result = 0;        while(y){            result = result*10 + y%10;            y = y/10;        }        return flag*result;    }};
思路很简单,就是取最后一位加到result上,然后乘以10,如此往复,取到原数的最高位,加到result上,result的最高位正好是原数的最低位。

但是现在问题来了,如果原数的反转数溢出的话,这样写就错了。

那现在想一下,只要得到的反转数比INT_MAX大,就会溢出,这个数在内存中就变了,所以没办法比较它和INT_MAX的大小。所以这里换一种思路,比较上一步结果和INT_MAX/10的大小,如果某一步result比INT_MAX/10大,并且这时y > 0,那么结果就会溢出。

这个代码AC了,但是仔细想想会带几个间谍进来。如果某个数,翻转的倒数第二个结果result == INT_MAX/10,并且剩下的最高位y>INT_MAX%10,也会溢出,所以也许要把这一部分排除掉。

这个方法其实就是在原来的方法上打了个补丁,实在想不出更好的办法了。

还有一个就是INT_MIN需要排除掉,这货取绝对值后比INT_MAX大1,直接溢出了。

class Solution {public:    int reverse(int x) {        if(x == INT_MIN) return false;        int flag = (x > 0) ? 1:-1;        int y =abs(x);        int result = 0;        while(y){            result = result*10 + y%10;            y = y/10;            if(result>(INT_MAX/10)&&y > 0 || result==(INT_MAX/10)&&y>INT_MAX%10) return false;        }        return flag*result;    }};

希望能抛砖引玉,大家如果想到更好的方法记得告诉我。


0 0