-
Notifications
You must be signed in to change notification settings - Fork 1
/
string-to-integer-atoi.cpp
44 lines (37 loc) · 1.13 KB
/
string-to-integer-atoi.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
class Solution {
public:
int myAtoi(string str) {
const auto& s = str;
const int n = str.length();
int start;
for (int i = 0; i < n; ++i) {
if (std::isspace(s[i])) {
continue;
}
if (s[i] == '-' || s[i] == '+' || std::isdigit(s[i])) {
start = i;
break;
} else {
return 0;
}
}
int sign = 1;
if (s[start] == '-' || s[start] == '+') {
if (s[start] == '-')
sign = -1;
++start;
}
long ret = 0;
for (int cur = start; cur < n && std::isdigit(s[cur]); ++cur) {
ret = ret * 10;
ret += sign * (s[cur] - '0');
if (ret < std::numeric_limits<int>::min()) {
return std::numeric_limits<int>::min();
}
if (ret > std::numeric_limits<int>::max()) {
return std::numeric_limits<int>::max();
}
}
return static_cast<int>(ret);
}
};