[LeetCode] 7. Reverse Integer

Posted arcsinw

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了[LeetCode] 7. Reverse Integer相关的知识,希望对你有一定的参考价值。

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的主要内容,如果未能解决你的问题,请参考以下文章

LeetCode 7. 整数反转 Reverse Integer

LeetCode 7. 整数反转 Reverse Integer

Leetcode 7. Reverse Integer(python)

LeetCode 7. Reverse Integer

Leetcode解题 7. Reverse Integer 反转整数

Leetcode-7 Reverse Integer