forked from liuyubobobo/Play-Leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
main3.cpp
55 lines (40 loc) · 1.25 KB
/
main3.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
55
/// Source : https://leetcode.com/problems/reverse-integer/description/
/// Author : liuyubobobo
/// Time : 2018-07-08
#include <iostream>
#include <vector>
#include <cassert>
using namespace std;
/// Poping digit one by one and check before overflow
/// Time Complexity: O(logx)
/// Space Complexity: O(1)
class Solution {
public:
int reverse(int x) {
if(x == 0)
return x;
if(x == INT_MIN)
return 0;
int sign = x > 0 ? 1 : -1;
x = abs(x);
int reverseNum = 0;
while(x){
if(reverseNum > INT_MAX / 10 || (reverseNum == INT_MAX / 10 && x % 10 > 7))
return 0;
reverseNum = reverseNum * 10 + x % 10;
x /= 10;
}
return sign * reverseNum;
}
};
int main() {
// cout << INT_MAX << endl; // 2147483647
// cout << INT_MIN << endl; // -2147483648
cout << Solution().reverse(123) << endl; // 321
cout << Solution().reverse(-123) << endl; // -321
cout << Solution().reverse(12) << endl; // 21
cout << Solution().reverse(INT_MAX) << endl; // 0
cout << Solution().reverse(INT_MIN) << endl; // 0
cout << Solution().reverse(-2147483412) << endl; // -2143847412
return 0;
}