/
7-ReverseInteger.cpp
54 lines (50 loc) · 1.42 KB
/
7-ReverseInteger.cpp
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
/*=============================================================================
# FileName: 7-ReverseInteger.cpp
# Desc: AC, 8ms
# Author: Jian Huang
# Email: huangjian1993@gmail.com
# HomePage: https://cn.linkedin.com/in/huangjian1993
# Version: 0.0.1
# LastChange: 2015-08-02 10:04:06
# History:
=============================================================================*/
#include <leetcode.h>
class Solution {
public:
int reverse(int x) {
if (x == 0) {
return 0;
}
bool negative = false;
long uX = 0;
if (x < 0) {
negative = true;
uX = -1 * long(x);
} else {
uX = x;
}
string str = "";
while (uX) {
str += '0' + uX % 10;
uX /= 10;
}
while (str[0] == '0') {
str = str.substr(1, str.length() - 1);
}
long result = 0;
int len = str.length();
for (int i = 0; i < len; i ++) {
result = result * 10 + (str[i] - '0');
if ((negative && result - 1 > INT_MAX) || (!negative && result > INT_MAX)) {
return 0;
}
}
return negative ? -result : result;
}
};
int main() {
Solution solution;
cout << solution.reverse(100001230) << endl;
cout << solution.reverse(INT_MAX) << endl;
cout << solution.reverse(-12348928) << endl;
}