Reverse Integer

https://leetcode.com/problems/reverse-integer/?tab=Description
Reverse digits of an integer.
Example1: x = 123, return 321
Example2: x = -123, return -321

这题如果是我想的话,肯定会想把它转换成数组然后首位往中间逼近着换位。。program creek把这种想法叫作Naive Method...因为这样需要分配额外空间。
事实上是有res = res * 10 + mod;这么个技巧存在,可以直接计算。注意判断边界。

    public int reverse(int x) {
        boolean flag = x > 0;
        if (!flag) {
            x = 0 - x;
        }
        int res = 0, mod = 0;
        while (x > 0) {
            mod = x % 10;
            //判断res边界  不是x边界
            if (res > (Integer.MAX_VALUE - mod )/ 10) {
                return 0;
            }
            res = res * 10 + mod;
            x = x / 10;
        }
        if (!flag) {
            return 0 - res;
        } else return res;
    }

另外,program creek里有一个答案,不需要判断正负号也是可以的。注意,-123 % 10结果是-3而不是3。上面的代码为了后面方便处理,先将数字转为正数。

已犯错误:

  1. 把res > (Integer.MAX_VALUE - mod )/ 10 的判断写成了对于x的判断。

你可能感兴趣的:(Reverse Integer)