forked from liuyubobobo/Play-Leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.cpp
44 lines (34 loc) · 983 Bytes
/
main.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
/// Source : https://leetcode.com/problems/reverse-integer/description/
/// Author : liuyubobobo
/// Time : 2018-07-08
#include <iostream>
using namespace std;
/// Using long long 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;
int sign = x > 0 ? 1 : -1;
long long num = abs(x);
long long reverseNum = 0;
while(num){
reverseNum = reverseNum * 10 + num % 10;
num /= 10;
}
reverseNum *= sign;
if(reverseNum > INT_MAX || reverseNum < INT_MIN)
return 0;
return reverseNum;
}
};
int main() {
cout << Solution().reverse(123) << endl;
cout << Solution().reverse(-123) << endl;
cout << Solution().reverse(12) << endl;
cout << Solution().reverse(INT_MAX) << endl;
cout << Solution().reverse(INT_MIN) << endl;
return 0;
}