-
Notifications
You must be signed in to change notification settings - Fork 0
/
#0008.string-to-integer-atoi.cpp
40 lines (37 loc) · 1.08 KB
/
#0008.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
class Solution {
public:
int myAtoi(string s) {
int length = s.length();
bool positive = true;
int index;
for (index = 0 ; index < length; ++index){
if (s[index] != ' ' && s[index] != '+' && s[index] != '-' && !isdigit(s[index])) {
return 0;
} else if(s[index] == ' '){
continue;
} else if(s[index] == '+'){
++index;
break;
} else if(s[index] == '-'){
++index;
positive = false;
break;
} else{
break;
}
}
long long result = 0;
for (int rindex = index; rindex < length; ++rindex) {
if (!isdigit(s[rindex])){
break;
}
result = result * 10 + (positive ? (s[rindex] - '0') : -(s[rindex] - '0'));
if (result > INT_MAX){
return INT_MAX;
} else if(result < INT_MIN){
return INT_MIN;
}
}
return (int) result;
}
};