Article From:https://www.cnblogs.com/arcsinw/p/9510806.html

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.


intReversal, 123 to 321. The point of this question is that temporary variables may spill out, and of course it’s mentioned in the title that if they spill out, they return to zero, and then I just look at Input and Output and start working on the problem until that WA

Judging an int overflow, notice that there may be a temporary variable overflow here at sum * 10, so do a move and become a division to prevent overflow

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

The complete code is as follows, plus io_sync_off is already 100%.

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;
}
Link of this Article: [LeetCode] 7. Reverse Integer

Leave a Reply

Your email address will not be published. Required fields are marked *