-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathstring_to_integer.cc
More file actions
40 lines (40 loc) · 1.18 KB
/
Copy pathstring_to_integer.cc
File metadata and controls
40 lines (40 loc) · 1.18 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
class Solution {
public:
int myAtoi(string str) {
int status = 0, sign = 1;
long long ans = 0;
for (char c:str) {
switch (status)
{
case 0: //init
if (isblank(c)) status = 0;
else if (isdigit(c)) {
ans=c-'0';
status = 1;
}
else if (c=='+' || c=='-') {
sign = (c=='+')?sign:-sign;
status = 1;
}
else status = 4;
break;
case 1: //signed
case 2:
if (isdigit(c)) {
ans*=10;
ans+=c-'0';
if (sign*ans > INT_MAX || sign*ans < INT_MIN) status = 4;
} else {
status = 4;
}
break;
case 4:
break;
}
}
ans *= sign;
if (ans<INT_MIN) ans = INT_MIN;
else if (ans>INT_MAX) ans = INT_MAX;
return static_cast<int>(ans);
}
};