forked from kamyu104/LintCode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
string-to-integeratoi.cpp
45 lines (39 loc) · 931 Bytes
/
string-to-integeratoi.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
// Time: O(n)
// Space: O(1)
class Solution {
public:
/**
* @param str: A string
* @return An integer
*/
int atoi(string str) {
if (str.empty()) {
return 0;
}
int ans = 0;
int sign = 1;
int i = 0;
// Skip ' '.
while (str[i] == ' ') {
++i;
}
// Parse sign.
if (str[i] == '+') {
++i;
} else if (str[i] == '-') {
sign = -1;
++i;
}
// Compute integer.
for (; i < str.length() && isdigit(str[i]); ++i) {
if (ans > (INT_MAX - (str[i] - '0')) / 10 ||
((str[i] - '0') == INT_MAX / 10 && (str[i] - '0') > INT_MAX % 10)) {
return sign > 0 ? INT_MAX : INT_MIN;
}
ans *= 10;
ans += str[i] - '0';
}
ans *= sign;
return ans;
}
};