-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path008_StringToInteger.cpp
53 lines (47 loc) · 1.04 KB
/
008_StringToInteger.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
//38.13
class Solution {
public:
int myAtoi(string str) {
long rst(0);
int index(str.find_first_not_of(' '));
int flag(1);
if(str[index] == '+' || str[index] == '-')
flag = (str[index++] == '-')?(-1):1;
//int size(str.size());
while(str[index] >= '0' && str[index] <= '9')
{
rst = rst * 10 + (str[index++] - '0');
if(rst * flag >= INT_MAX)
return INT_MAX;
if(rst * flag <= INT_MIN)
return INT_MIN;
}
return rst * flag;
}
};
//10.09%
class Solution001 {
public:
int myAtoi(string str) {
long rst(0);
int index = str.find_first_not_of(' ');
int flag(1);
if(str[index] == '+' || str[index] == '-')
flag = (str[index++] == '-')?(-1):1;
int size = str.size();
while(index < size)
{
if(str[index] >= '0' && str[index] <= '9')
{
rst = rst * 10 + (str[index++] - '0');
if(rst * flag >= INT_MAX)
return INT_MAX;
if(rst * flag <= INT_MIN)
return INT_MIN;
}
else
break;
}
return rst * flag;
}
};