-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathatoi.cpp
More file actions
54 lines (44 loc) · 1.3 KB
/
atoi.cpp
File metadata and controls
54 lines (44 loc) · 1.3 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
45
46
47
48
49
50
51
52
53
54
class Solution {
public:
int myAtoi(string str) {
int flg = 1, pos = 0, cnt = 0;
long ret = 0;
/* whether it is empty */
if (str.empty())
return 0;
/* pass whitespace */
while (str[pos] == '\r' || str[pos] == ' ')
pos++;
/* check whether there has a illegal character */
if (str[pos] != '+' && str[pos] != '-' && str[pos] < '0' && str[pos] > '9')
return 0;
/* check the sign */
if (str[pos] == '-')
{
flg = -1;
pos++;
}
else if (str[pos] == '+')
pos++;
/* check whether there is a reduplicate sign */
if (str[pos] == '-' || str[pos] == '+')
return 0;
while (pos < str.size())
{
if (str[pos] < '0' || str[pos] > '9')
break;
ret = ret*10 + str[pos] - '0';
cnt++;
pos++;
}
/* whether it is overflow */
if (cnt > 10)
return (flg > 0 ? INT_MAX : INT_MIN);
ret *= flg;
if (ret > INT_MAX)
return INT_MAX;
if (ret < INT_MIN)
return INT_MIN;
return (int) ret;
}
};