-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path0008-string-to-integer-atoi.cpp
48 lines (45 loc) · 1.16 KB
/
0008-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
45
46
47
48
class Solution {
public:
int myAtoi(string str) {
bool sign = false;
bool start = false;
long value = 0;
for(int i = 0; i < str.size(); i++) {
//" "
if(!start && str[i] == 32) {
continue;
}
//"-"
if(!start && str[i] == 45) {
start = true;
sign = true;
continue;
}
//"+"
if(!start && str[i] == 43) {
start = true;
continue;
}
if(str[i] < 48 || str[i] > 57) {
break;
}
if(!start && 48 <= str[i] && str[i] <= 57) {
start = true;
}
if(sign) {
value = value*10-(str[i] - 48);
if(value <= INT_MIN) {
value = INT_MIN;
break;
}
} else {
value = value*10+(str[i] - 48);
if(value >= INT_MAX) {
value = INT_MAX;
break;
}
}
}
return value;
}
};