7. 整数反转
为保证权益,题目请参考 7. 整数反转(From LeetCode).
解决方案1
CPP
C++
#include <iostream>
#include <limits.h>
using namespace std;
class Solution
{
public:
int reverse(int x)
{
int res = 0;
while (x)
{
int n = x % 10;
x = x / 10;
if (res > INT_MAX / 10 || (res == INT_MAX / 10 && x > INT_MAX % 10))
{
res = -1;
break;
}
if (res < INT_MIN / 10 || (res == INT_MIN / 10 && x < INT_MIN % 10))
{
res = -1;
break;
}
res = res *10 + n;
}
return res;
}
};
int main()
{
return 0;
}
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
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