原题目为:

Reverse digits of an integer.
Example1: x = 123, return 321

Example2: x = -123, return -321

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.

难度: Easy

此题让我们输出给定一个整数的倒序数, 比如123倒序为321, -123倒序为-321. 但是如果倒序的过程中发生整型溢出, 我们就输出0.

倒序不复杂, 关键在于如何判定将要溢出.

最终AC的程序如下:

public class Solution {

    public int reverse(int x) {
        int x1 = Math.abs(x);
        int rev = 0;
        while (x1 > 0) {
            if (rev > (Integer.MAX_VALUE - (x1 - (x1 / 10) * 10)) / 10) {
                return 0;
            }
            rev = rev * 10 + (x1 - (x1 / 10) * 10);
            x1 = x1 / 10;
        }
        if (x > 0) {
            return rev;
        } else {
            return -rev;
        }
    }
}

其中 x1 - (x1 / 10) * 10 是获取x1的个位数字, 判定下一步是否将要溢出, 使用 rev > (Integer.MAX_VALUE - (x1 - (x1 / 10) * 10)) / 10 .


EthanSun
45 声望3 粉丝