7. Reverse Integer

题目:

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.

Hide Tags
 Math 

链接: http://leetcode.com/problems/reverse-integer/

题解:

reverse一个整数,主要考察乘10时的overflow的问题。可以设置一个条件,当临时结果大于Integer.MAX_VALUE / 10或者临时结果小于Integer.MIN_VALUE / 10的时候,后面运算乘10肯定会溢出,所以直接return 0给出结果。

不需要处理当临时结果等于Integer.MAX_VALUE或者Integer.MIN_VALUE时的情况, 因为Integer.MAX_VALUE = 214783647,Integer.MIN_VALUE = -214783648。除以10为 21478364或者 - 21478364,假如输入是有效的Integer,最后一位必为1,否则输入不在32位int的范围里。所以此时 x % 10 = 1,临时结果result乘10再加1后不会造成最终结果溢出。

Time Complexity - O(logx), Space Complexity - O(1)。

public class Solution {
    public int reverse(int x) {
        if(x == 0)
            return 0;
        int result = 0;
while(x != 0){ if(result > Integer.MAX_VALUE / 10 || result < Integer.MIN_VALUE / 10) return 0; result = result * 10 + x % 10; x /= 10; } return result; } }

二刷:

Java:

可以AC的不严谨做法。 Time Complexity - O(lgx), Space Complexity - O(1)

public class Solution {
    public int reverse(int x) {
        int res = 0;
        while (x != 0) {
            if (res > Integer.MAX_VALUE / 10 || res < Integer.MIN_VALUE / 10) {
                return 0;
            }
            res = res * 10 + x % 10;
            x /= 10;
        }
        
        return res;
    }
}

Python:

Python的版本不能套用Java的方法,因为Python里mod总是返回相同符号。这里完全照搬了StefanPochmann大神的写法。先用cmp(x, 0)求出符号,再把正数s * x用``符号转换为string,逆序遍历之后再乘以符号,同时乘以绝对值与 2 ** 31的比较。写法确实比较巧妙。

class Solution(object):
    def reverse(self, x):
        s = cmp(x, 0)
        r = int(`s*x`[::-1])
        return s*r * (r < 2**31)
    

三刷:

这种数值计算题,假如遇到的话,要跟面试官详细讨论边界条件,溢出应该怎么做。

Java:

public class Solution {
    public int reverse(int x) {
        int res = 0;
        while (x != 0) {
            if (res > Integer.MAX_VALUE / 10 || res < Integer.MIN_VALUE / 10) return 0;
            res = res * 10 + x % 10;
            x /= 10;
        }
        return res;
    }
}

Reference:

https://leetcode.com/discuss/39594/golfing-in-python 

原文地址:https://www.cnblogs.com/yrbbest/p/4430339.html