[Day2]7. Reverse Integer

2017-01-31  本文已影响0人  Shira0905

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

The description is really short and easy.
The solution of my own takes 49ms, the most voted solution in Java takes 41ms.

Before my AC, I got two WA because of I didn't take the range of Integer into consideration. So, I add the 'if' to judge whether the reversed number is beyond the range of 'Integer'.

!But, one point that really makes me confused is that why the top solution didn't face the problem of integer range. ! ->->

public static int reverse(int x) {
    ArrayList<Integer> a = new ArrayList<Integer>();
    int s = x / 10;
    int y = x % 10;
    a.add(y);
    while (s != 0) {
        y = s % 10;
        s = s / 10;
        a.add(y);
    }
    int l = a.size();
    int r = 0;
    for (int i = 0; i < l; i++) {
        if (r + a.get(l - 1 - i) * Math.pow(10, i) > Integer.MAX_VALUE
                || r + a.get(l - 1 - i) * Math.pow(10, i) < Integer.MIN_VALUE)
            return 0;
        r = (int) (r + a.get(l - 1 - i) * Math.pow(10, i));
    }
    return r;
}

public int reverseTop(int x) {
    int result = 0;
    while (x != 0) {
        int tail = x % 10;
        int newResult = result * 10 + tail;
        if ((newResult - tail) / 10 != result) {
            return 0;
        }
        result = newResult;
        x = x / 10;
    }
    return result;
}
上一篇 下一篇

猜你喜欢

热点阅读