forked from PRIYANSHU-KESHRI/hackoct-2k22
-
Notifications
You must be signed in to change notification settings - Fork 0
/
7. Reverse Integer.cpp
61 lines (51 loc) · 1.67 KB
/
7. Reverse Integer.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
//Runtime: 4 ms, faster than 55.26% of C++ online submissions for Reverse Integer.
//Memory Usage: 6.2 MB, less than 12.99% of C++ online submissions for Reverse Integer.
class Solution {
public:
int reverse(int x) {
bool neg = false;
if(x < 0){
neg = true;
long long tmp = x * -1LL;
//consider -2147483648
if(tmp > INT_MAX) return 0;
x = tmp;
}
int ans = 0;
while(x){
long long tmp = ans * 10LL + x % 10;
//consider 1534236469
if(tmp > INT_MAX) return 0;
ans = tmp;
x /= 10;
}
if(neg){
ans *= -1;
}
return ans;
}
};
//Approach 1: Pop and Push Digits & Check before Overflow
//Runtime: 4 ms, faster than 55.26% of C++ online submissions for Reverse Integer.
//Memory Usage: 6.1 MB, less than 22.79% of C++ online submissions for Reverse Integer.
//time: O(log10(x)), space: O(1)
class Solution {
public:
int reverse(int x) {
int ans = 0;
while(x){
int pop = x%10;
x /= 10;
//>7 because the last digit of INT_MAX is 7
//if ans*10 > INT_MAX or ans*10+pop > INT_MAX
if(ans > INT_MAX/10 || (ans == INT_MAX/10 && pop > 7))
return 0;
//<-8 because the last digit of INT_MIN is 8
//if ans*10 < INT_MIN or ans*10+pop < INT_MIN
if(ans < INT_MIN/10 || (ans == INT_MIN/10 && pop < -8))
return 0;
ans = ans*10 + pop;
}
return ans;
}
};