首页 > 其他 > 详细

[LeetCode] 7. Reverse Integer

时间:2018-08-21 13:36:23      阅读:142      评论:0      收藏:0      [点我收藏+]

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

原文:https://www.cnblogs.com/arcsinw/p/9510806.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!