forked from walkccc/LeetCode
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path0008.cpp
More file actions
29 lines (26 loc) · 758 Bytes
/
0008.cpp
File metadata and controls
29 lines (26 loc) · 758 Bytes
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
class Solution {
public:
int myAtoi(string str) {
long long ans = 0;
bool isNegative = false;
int j = 0;
while (j < str.size() && str[j] == ' ') j++;
if (j == str.size()) return 0;
if (str[j] == '-') {
isNegative = true;
j++;
} else if (str[j] == '+') {
j++;
}
for (int i = j; i < str.size(); i++) {
if (str[i] < '0' || str[i] > '9')
break;
else {
ans = ans * 10 + (str[i] - '0');
if (isNegative && -ans <= INT_MIN) return INT_MIN;
if (!isNegative && ans >= INT_MAX) return INT_MAX;
}
}
return isNegative ? -ans : ans;
}
};