[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;
}
最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容