7. Reverse Integer

难点在溢出,如果是python的话还要考虑符号,因为python中-123 % 10 = 7

预先计算

public int reverse(int x) {
    int res = 0;
    while (x != 0) {
        if (Integer.MAX_VALUE / 10 == res && Integer.MAX_VALUE % 10 < (x % 10) || Integer.MAX_VALUE / 10 < res) return 0;
        if (Integer.MIN_VALUE / 10 == res && Integer.MIN_VALUE % 10 > (x % 10) || Integer.MIN_VALUE / 10 > res) return 0;
        res = res * 10 + x % 10;
        x = x / 10;
    }
    return res;
}

中间和旧值进行比较

public int reverse(int x) {
    int res = 0, cmp = 0;
    while (x != 0) {
        cmp = cmp * 10 + x % 10;
        if ((cmp -(x % 10)) / 10 != res) return 0;
        x = x / 10;
        res = cmp;
    }
    return res;
}

-2147483648为例子,输出结果为

0
-8
-84
-846
-8463
-84638
-846384
-8463847
-84638474
12608718

然后有些答案里是res为long直接判断。

results matching ""

    No results matching ""