generated from threeal/project-starter
-
Notifications
You must be signed in to change notification settings - Fork 1
/
solution.cpp
48 lines (41 loc) · 998 Bytes
/
solution.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
#include <string>
class Solution {
public:
int myAtoi(std::string s) {
const int n = s.size();
int i;
for (i = 0; i < n; ++i) {
if (s[i] >= '0' && s[i] <= '9') break;
switch (s[i]) {
case ' ':
break;
case '+':
case '-':
if (i + 1 >= n) return 0;
if (s[i + 1] < '0' || s[i + 1] > '9') return 0;
break;
default:
return 0;
}
}
const bool neg = i > 0 && s[i - 1] == '-';
int total = 0;
for (; i < n; ++i) {
if (s[i] < '0' || s[i] > '9') break;
if (neg) {
if (total <= -214748364) {
if (total < -214748364 || s[i] - '0' >= 8)
return -2147483648;
}
total = total * 10 - (s[i] - '0');
} else {
if (total >= 214748364) {
if (total > 214748364 || s[i] - '0' >= 7)
return 2147483647;
}
total = total * 10 + (s[i] - '0');
}
}
return total;
}
};