[Day2]7. Reverse Integer

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;
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容