07 Reverse Integer

/7. Reverse Integer

Reverse digits of an integer.

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

Note:

The input is assumed to be a 32-bit signed integer. Your function should

return 0 when the reversed integer overflows.

代码& 分析

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.

就像spoiler所说,这么简单的题目,坑点就在于会溢出。

自己的思路是,转换成long,翻转,判断有没有超过Integer的边界,返回值,但是不漂亮,很多判断,看到一种方法很好,自己写了一遍

 public int reverse(int x) {
    int result = 0;
    while(x != 0) {
        int tail = x % 10;
        int nextRes = result * 10 + tail;
        if((nextRes - tail) / 10 != result) {
            return 0;
        }
        result = nextRes;
        x = x / 10;
    }
    return result;
}

这个方法的亮点:

  • 判断是否溢出,看这次原样退回的结果,和上一步的结果是否相同,因为如果溢出了,结果肯定就不同了,而且如果溢出了就立刻跳出,不需要继续循环了
  • 循环的退出条件不是x > 0而是x != 0,使得我们不需要对x < 0的情况分开讨论

results matching ""

    No results matching ""