-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path0007-reverse-integer.cpp
More file actions
44 lines (42 loc) · 1.11 KB
/
0007-reverse-integer.cpp
File metadata and controls
44 lines (42 loc) · 1.11 KB
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
#include <limits.h>
class Solution {
public:
int reverse(int x) {
if (x == 0x80000000) {
return 0;
}
int absVal = x;
if (x < 0) {
absVal = ~absVal + 0x1;
}
// what is the most significant place value
int tVal = absVal;
int place = 0;
while (tVal/10 > 0) {
tVal /= 10;
place++;
}
// prepare to load digits
int fact = 1;
for (int i = 0; i < place; i++) {
fact *= 10;
}
int finalVal = 0;
char safe = 0;
for (int i = 0; i <= place; i++) {
if (place == 9 && safe == 0 && (((0x7FFFFFFF/fact) % 10) < (absVal%10))) {
return 0;
} else if (place == 9 && safe == 0 && (((0x7FFFFFFF/fact) % 10) > (absVal%10))) {
safe = 1;
}
finalVal += fact*(absVal % 10);
fact /= 10;
absVal /= 10;
}
if (x < 0) {
finalVal = ~finalVal + 0x1;
}
// outside of signed int range??
return finalVal;
}
};