-
Notifications
You must be signed in to change notification settings - Fork 0
/
string_to_integer(atoi).cpp
57 lines (51 loc) · 1.33 KB
/
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
49
50
51
52
53
54
55
56
57
class Solution {
public:
int myAtoi(string str) {
if (str.size() == 0)
return 0;
auto it = str.begin();
//clear '0' or ' ' in front
while (it != str.end() && (*it == 0 || *it == ' ')) ++it;
bool negative = false;
if (*it == '-')
{
negative = true;
++it;
if (!is_num(*it))
return 0;
}
if (*it == '+')
{
++it;
if (!is_num(*it))
return 0;
}
//clear '0' behind '-' in front of nums
while (it != str.end() && *it == 0) ++it;
long result = 0;
long int_max = numeric_limits<int>::max();
long int_min = numeric_limits<int>::min();
for(; it != str.end() && is_num(*it); ++it)
{
int num = *it - '0';
result = 10 * result + num;
if (result > int_max)
break;
}
if (negative)
{
result = -result;
if (result < int_min)
return int_min;
return result;
}
// positive
if (result > int_max)
return int_max;
return result;
}
bool is_num(char ch)
{
return ch >= '0' && ch <= '9';
}
};