-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathStringToInteger.cpp
53 lines (50 loc) · 1.27 KB
/
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
class Solution {
public:
int atoi(const char *str) {
if ((NULL == str) || (strlen(str) == 0)) {
return 0;
}
const char* p = str;
while (' ' == *p) {
++p;
}
int negative = 1;
if ('-' == *p) {
negative = -1;
++p;
}
else if ('+' == *p){
negative = 1;
++p;
}
else if ((*p < '0') || (*p > '9')) {
return 0;
}
else {
}
int result = 0;
while (*p != '\0') {
if ((*p) < '0' || (*p) > '9') {
break;
}
if ((*p) != ' ') {
int bit = (*p) - '0';
if (1 == negative) {
int maxInt = std::numeric_limits<int>::max();
if (result > (maxInt-bit)/10) {
return maxInt;
}
}
else {
int minInt = std::numeric_limits<int>::min();
if (-result < (minInt+bit)/10) {
return minInt;
}
}
result = result*10 + bit;
}
++p;
}
return result * negative;
}
};