-
Notifications
You must be signed in to change notification settings - Fork 0
/
LC8stringToIntegerAtoi.cpp
57 lines (56 loc) · 1.72 KB
/
LC8stringToIntegerAtoi.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
#include <string>
class Solution {
public:
inline bool check_overflow_pos(int a[], int i) {
int b[10] = {2, 1, 4, 7, 4, 8, 3, 6, 4, 7};
if (i < 10) return true;
if (i > 10) return false;
for (int p = 0; p < 10; p++) {
if (a[p] < b[p]) {
return true;
} else if (a[p] > b[p]) {
return false;
}
}
return true;
}
inline bool check_overflow_neg(int a[], int i) {
int b[10] = {2, 1, 4, 7, 4, 8, 3, 6, 4, 8};
if (i < 10) return true;
if (i > 10) return false;
for (int p = 0; p < 10; p++) {
if (a[p] < b[p]) {
return true;
} else if (a[p] > b[p]) {
return false;
}
}
return true;
}
inline bool check_overflow(int a[], int i, bool sign) {
return sign ? check_overflow_pos(a, i) : check_overflow_neg(a, i);
}
int myAtoi(string s) {
int j = 0, l = s.length(), k = 0, i[200];
while (s[j] == ' ' && j < l) j++;
if (s[j] != '+' && s[j] != '-' && (s[j] < 48 || s[j] > 57)) return 0;
bool sign = true;
switch (s[j]) {
case '-':
sign = false;
j++;
break;
case '+':
j++;
}
if (s[j] < 48 || s[j] > 57) return 0;
while (s[j] == '0') j++;
while (j < l && 48 <= s[j] && s[j] <= 57) i[k++] = s[j++] - 48;
int res = 0;
if (!check_overflow(i, k, sign)) return sign ? 2147483647 : -2147483648;
for (int p = 0; p < k; p++) {
res = sign ? (10 * res + i[p]) : (10 * res - i[p]);
}
return res;
}
};