【LeetCode】007. Reverse Integer

时间:2023-03-09 16:51:29
【LeetCode】007. 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 hold integers within the 32-bit signed integer range. For the purpose of this problem, assume that your function returns 0 when the reversed integer overflows.

题解:

   难点在于溢出的判断上。当 abs(res) 大于等于 INT_MAX / 10 时,就需要判断结果是否要溢出了。INT_MIN = -2147483648,INT_MAX = 2147483647。这里为什么不需要在

 class Solution {
public:
int reverse(int x) {
int res = ;
while (x) {
int digit = x % ;
if (abs(res) > INT_MAX / || res == INT_MAX / && digit > || res == INT_MIN / && digit < -)
return ;
res = res * + digit;
x /= ;
} return res;
}
};

    其实在 abs(res) == INT_MAX / 10 时可以直接做溢出处理,原因是输入 x 是 int 类型,所以 x 的范围也应该在 INT_MIN 和 INT_MAX 之间,那么 x 的第一位只能是1或者2,x 翻转之后 res 的最后一位只能是1或2。当 abs(res) == INT_MAX / 10时,下一步的 res 只能是 (-)2147483641 或 (-)2147483642,对应的 x 为 1463847412 和 2463847412,而2463847412 超出了 int 的数值范围。所以当 res 等于 214748364 时, 输入的 x 只能为 1463847412, 翻转后的结果 res 为 2147483641,在正确的范围内。

  

 class Solution {
public:
int reverse(int x) {
int res = ;
while (x) {
int digit = x % ;
if (abs(res) > INT_MAX / )
return ;
res = res * + digit;
x /= ;
} return res;
}
};

转自:Grandyang