# 整数反转
给你一个 32 位的有符号整数 x
,返回将 x
中的数字部分反转后的结果。
如果反转后整数超过 32 位的有符号整数的范围 [−231, 231 − 1]
,就返回 0。
假设环境不允许存储 64 位整数(有符号或无符号)。
示例 1:
输入:x = 123
输出:321
示例 2:
输入:x = -123
输出:-321
示例 3:
输入:x = 120
输出:21
示例 4:
输入:x = 0
输出:0
提示:
以下错误的选项是?
## aop
### before
```c
#include
using namespace std;
```
### after
```c
int main()
{
Solution test;
int ret;
int x = -123;
int numrows = 3;
ret = test.reverse(x);
cout << ret << endl;
return 0;
}
```
## 答案
```c
class Solution
{
public:
int reverse(int x)
{
long n = 0;
while (x)
{
n = x % 10 + n * 10;
x /= 10;
}
return n > INT_MAX || n < INT_MIN ? n : 0;
}
};
```
## 选项
### A
```c
class Solution
{
public:
int reverse(int x)
{
int MAX = 0x7fffffff;
int MIN = 1 << 31;
ostringstream stream, smax, smin;
string ss;
stream << x;
ss += stream.str();
smax << MAX;
string max_num = smax.str();
smin << MIN;
string min_num = smin.str();
std::reverse(ss.begin(), ss.end());
if (x < 0)
{
ss.insert(0, "-");
ss.pop_back();
}
if (x > 0 && ss.size() >= max_num.size() && (ss > max_num))
return 0;
else if (x < 0 && ss.size() >= min_num.size() && ss > min_num)
return 0;
else
return atoi(ss.c_str());
}
};
```
### B
```c
class Solution
{
public:
#define INT_MAX 2147483647
#define INT_MIN (-INT_MAX - 1)
int reverse(int x)
{
int flag = x < 0 ? -1 : 1;
int num = 0;
while (x)
{
if ((flag == -1 && (INT_MIN / 10 > num)) || (flag == 1 && INT_MAX / 10 < num))
return 0;
num = num * 10 + x % 10;
x /= 10;
}
return num;
}
};
```
### C
```c
class Solution
{
public:
int reverse(int x)
{
int rev = 0;
while (x != 0)
{
int pop = x % 10;
x = x / 10;
if (rev > INT_MAX / 10 || (rev == INT_MAX / 10 && pop > 7))
return 0;
if (rev < INT_MIN / 10 || (rev == INT_MIN / 10 && pop < -8))
return 0;
rev = rev * 10 + pop;
}
return rev;
}
};
```