[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_INT, sum > 0
sum * 10 + x % 10 < MIN_INT, sum < 0
sum > (MAX_INT - x % 10) / 10, sum > 0
sum < (MIN_INT - x % 10) / 10, sum < 0
完整代码如下,加上io_sync_off已经能100.0%了
int reverse(int x)
{
int sum = 0;
int MAX_INT = 2147483647;
int MIN_INT= -2147483648;
while (x)
{
if ((sum > 0 && sum > (MAX_INT - x % 10) / 10) ||
(sum < 0 && sum < (MIN_INT - x % 10) / 10))
{
return 0;
}
sum = sum * 10 + x % 10;
x /= 10;
}
return sum;
}