forked from black-shadows/LeetCode-Topicwise-Solutions
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathstring-to-integer-atoi.cpp
44 lines (37 loc) · 966 Bytes
/
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
// Time: O(n)
// Space: O(1)
class Solution {
public:
int myAtoi(string str) {
if (str.empty()) {
return 0;
}
int ans = 0;
int sign = 1;
int i = 0;
// Skip whitespace.
while (str[i] == ' ' || str[i] == '\t') {
++i;
}
if (i == str.length()) {
return 0;
}
// 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 > (numeric_limits<int>::max() - (str[i] - '0')) / 10) {
return sign > 0 ? numeric_limits<int>::max() : numeric_limits<int>::min();
}
ans *= 10;
ans += str[i] - '0';
}
ans *= sign;
return ans;
}
};