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.
int reverse(int x)
{
long long val = 0;
do
{
val = val * 10 + x % 10;
x /= 10;
} while (x);
return (val > INT_MAX || val <INT_MIN) ? 0:(int)val;
}
C++实现:
```
class Solution {
public:
int reverse(int x) {
int64_t res = 0;
while(x){
res = res * 10 + x%10;
x /= 10;
if(!check_valid(res)) return 0;
}
return res;
}
private:
bool check_valid(int64_t x) {
if(x < INT_MIN || x > INT_MAX)
return false;
return true;
}
};
上面这种方法实际上是一种取巧的方法,利用了int64_t表示范围大过int32_t这一事实,实际上不用int64_t同样可以完美的解决这一问题。如果乘以10以后有可能溢出,那么可以对INT_MAX INT_MIN除以10判断。
class Solution {
public:
int reverse(int x) {
int reverse = 0;
while(x){
int p = x % 10;
if(reverse > INT_MAX/10 || reverse == INT_MAX/10 && p > 7) return 0;
if(reverse < INT_MIN/10 || reverse == INT_MIN/10 && p < -8) return 0;
x /= 10;
reverse = reverse*10 + p;
}
return reverse;
}
};
2021.05.25更新
/* Minimum and maximum values a `signed int' can hold. */
define INT_MIN (-INT_MAX - 1)
define INT_MAX 2147483647
INT_MAX 2147483647 INT_MIN -2147483648
题目中的限定条件是环境不允许存储64位整数,因此我们在每次乘10之前判断是否越界即可。