forked from liuyubobobo/Play-Leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
main2.cpp
78 lines (60 loc) · 1.92 KB
/
main2.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
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
/// Source : https://leetcode.com/problems/reverse-integer/description/
/// Author : liuyubobobo
/// Time : 2018-07-08
#include <iostream>
#include <vector>
#include <cassert>
using namespace std;
/// Using digit vector to solve the overflow problem
/// Time Complexity: O(logx)
/// Space Complexity: O(logx)
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);
vector<int> reverseDigits;
while(x){
reverseDigits.push_back(x % 10);
x /= 10;
}
if(sign > 0 && overflow(reverseDigits, {2, 1, 4, 7, 4, 8, 3, 6, 4, 7}))
return 0;
else if(sign < 0 && overflow(reverseDigits, {2, 1, 4, 7, 4, 8, 3, 6, 4, 8}))
return 0;
return sign * getNumber(reverseDigits);
}
private:
int getNumber(const vector<int>& digits){
int res = 0;
for(int digit: digits)
res = res * 10 + digit;
return res;
}
bool overflow(const vector<int>& digits, const vector<int>& max){
if(digits.size() < max.size())
return false;
assert(digits.size() == max.size());
for(int i = 0 ; i < digits.size() ; i ++)
if(digits[i] > max[i])
return true;
else if(digits[i] < max[i])
return false;
return false;
}
};
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;
}