solution.md 2.1 KB
Newer Older
每日一练社区's avatar
每日一练社区 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121
# 整数反转
以下错误的选项是?
## aop
### before
```cpp
#include <bits/stdc++.h>
using namespace std;
```
### after
```cpp
int main()
{
    Solution test;

    int ret;
    int x = -123;
    int numrows = 3;
    ret = test.reverse(x);
    cout << ret << endl;
    return 0;
}

```

## 答案
```cpp
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
```cpp
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
```cpp
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
```cpp
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;
    }
};
```