#include <climits>
class Solution {
public:
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param x int整型
* @return int整型
*/
const int INT_MAX_BOUND = 147483647;
const int INT_MIN_BOUND = -147483648;
int reverse(int x) {
int ans = 0, length = 0;
// 提取最低位数字,因为在反转后,最低位数字将变为为最高位数字
int lowest_digit = x % 10;
x /= 10;
// 将剩余部分反转
while (x) {
ans = ans * 10 + x % 10;
x /= 10;
++length;
}
if (length == 9) {
// 检测所有溢出情况
if (lowest_digit > 2 ||
lowest_digit < -2 ||
(lowest_digit == 2 && ans > INT_MAX_BOUND) ||
(lowest_digit == -2 &&
ans < INT_MIN_BOUND)) {
ans = 0;
} else {
ans = lowest_digit * pow(10, length) + ans;
}
} else {
ans = lowest_digit * pow(10, length) + ans;
}
return ans;
}
};