/
008_atoi.cpp
42 lines (42 loc) · 905 Bytes
/
008_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
class Solution {
public:
int myAtoi(string str)
{
int negative = 0, res = 0, i = 0;
while (true)
{
if (str[i] == ' ')
i++;
else
break;
}
if (str[i] == '-')
{
negative = 1;
i++;
}else if (str[i] == '+')
{
i++;
}
else if (!(str[i] - '0' >= 0 && '9' - str[i] >= 0))
return 0;
vector<int> v;
while (str[i] - '0' >= 0 && '9' - str[i] >= 0)
{
int temp = str[i++] - '0';
if (negative)
temp = -temp;
v.push_back(temp);
}
while (!v.empty())
{
if ((res > INT_MAX / 10) || (res == INT_MAX / 10 && v.front() > 7))
return INT_MAX;
if ((res < INT_MIN / 10) || (res == INT_MIN / 10 && v.front() < -8))
return INT_MIN;
res = res * 10 + v.front();
v.erase(v.begin());
}
return res;
}
};