# 整数反转

<p>给你一个 32 位的有符号整数 <code>x</code> ，返回将 <code>x</code> 中的数字部分反转后的结果。</p><p>如果反转后整数超过 32 位的有符号整数的范围 <code>[−2<sup>31</sup>,  2<sup>31 </sup>− 1]</code> ，就返回 0。</p><strong>假设环境不允许存储 64 位整数（有符号或无符号）。</strong><p> </p><p><strong>示例 1：</strong></p><pre><strong>输入：</strong>x = 123<strong><br />输出：</strong>321</pre><p><strong>示例 2：</strong></p><pre><strong>输入：</strong>x = -123<strong><br />输出：</strong>-321</pre><p><strong>示例 3：</strong></p><pre><strong>输入：</strong>x = 120<strong><br />输出：</strong>21</pre><p><strong>示例 4：</strong></p><pre><strong>输入：</strong>x = 0<strong><br />输出：</strong>0</pre><p> </p><p><strong>提示：</strong></p><ul>	<li><code>-2<sup>31</sup> <= x <= 2<sup>31</sup> - 1</code></li></ul>
<p>以下<span style="color:red">错误</span>的选项是？</p>

## aop

### before

```c
#include <bits/stdc++.h>
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;
    }
};
```
