Reverse Integer

题目:

Reverse digits of an integer. Returns 0 when the reversed integer overflows (signed 32-bit integer).

补充: (2016-10-30) 忘记了负整数的情况...而且直接开了个double没开long...这实在是手生了啊

分析:

就说两点

1. 有可能是negative integer,这一点需要考虑
2. 有可能反过来以后超过INT_MAX,这种情况下return 0

但是我觉得其实反过来超过范围这个要求是不合理的...

解法:

public class Solution {
    /**
     * @param n the integer to be reversed
     * @return the reversed integer
     */
    public int reverseInteger(int n) {
        // Write your code here
        boolean flag = true;
        if (n < 0) {
            flag = false;
        }
        int absN = n;
        if (!flag) {
            absN = Math.abs(n);
        }
        long absRes = 0;
        while (absN != 0) {
            int temp = absN % 10;
            absN /= 10;
            absRes = absRes * 10 + temp;
        }
        if (absRes > Integer.MAX_VALUE) {
            return 0;
        }
        if (!flag) {
            absRes = -absRes;
        }
        return (int) absRes;
    }
}

results matching ""

    No results matching ""