-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path0008.string-to-integer-atoi.cpp
More file actions
44 lines (34 loc) · 1 KB
/
0008.string-to-integer-atoi.cpp
File metadata and controls
44 lines (34 loc) · 1 KB
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
// https://leetcode.com/problems/string-to-integer-atoi/
class Solution {
public:
int myAtoi(string s) {
int i = 0;
int len = s.length();
int isPositive = true;
int result = 0;
while (i < len && s[i] == ' ') i++;
if (s[i] == '-' || s[i] == '+') {
if (s[i] == '-') isPositive = false;
i++;
}
while (i < len) {
char c = s[i];
if (!isdigit(c)) return result;
if (isPositive) {
if (result > INT_MAX / 10) return INT_MAX;
result *= 10;
int n = c - '0';
if (result > INT_MAX - n) return INT_MAX;
result += n;
} else {
if (result < INT_MIN / 10) return INT_MIN;
result *= 10;
int n = c - '0';
if (result < INT_MIN + n) return INT_MIN;
result -= n;
}
i++;
}
return result;
}
};