1. 程式人生 > >[LeetCode] 7. Reverse Integer

[LeetCode] 7. Reverse Integer

signed lee eal example pos sum pro 臨時變量 dea

Given a 32-bit signed integer, reverse digits of an integer.

Example 1:

Input: 123
Output: 321

Example 2:

Input: -123
Output: -321

Example 3:

Input: 120
Output: 21

Note:

Assume we are dealing with an environment which could only store integers within the 32-bit signed integer range: [?231, 231 ? 1]. For the purpose of this problem, assume that your function returns 0 when the reversed integer overflows.


int反轉,123變321。這道題的重點在於臨時變量可能溢出,當然題目裏也提到了這一點要是溢出就返回0,然後我只看了Input和Output就開始做題了,直到那個WA

判斷int溢出,註意這裏可能在sum * 10的時候發生臨時變量溢出,所以做一下移項,變成除法防止溢出

sum * 10 + x % 10 > MAX_P_INT, sum > 0
sum * 10 + x % 10 < MAX_N_INT, sum < 0

sum > (MAX_P_INT - x % 10) / 10, sum > 0
sum < (MAX_N_INT - x % 10) / 10, sum < 0

完整代碼如下,加上io_sync_off已經能100.0%了

int reverse(int x)
{
    int sum = 0;
    int MAX_P_INT = 2147483647;
    int MAX_N_INT= -2147483648;

    while (x)
    {
        if ((sum > 0 && sum > (MAX_P_INT - x % 10) / 10) ||
            (sum < 0 && sum < (MAX_N_INT - x % 10) / 10))
        {
            return 0;
        }

        sum = sum * 10 + x % 10;
        x /= 10;
    }

    return sum;
}

[LeetCode] 7. Reverse Integer