-
Notifications
You must be signed in to change notification settings - Fork 28
/
Copy pathString_to_Integer_(atoi).cpp
49 lines (41 loc) · 1.22 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
class Solution {
public:
int myAtoi(string str) {
if(str.empty()) return 0;
int i = 0;
bool positive = true;
int result = 0;
// removing white space
while(str[i] == ' ') {
i++;
}
// checking sign
if(str[i] == '-') {
positive = false;
i++;
} else if(str[i] == '+') {
positive = true;
i++;
}
if(!isdigit(str[i])) {
return 0;
}
while(isdigit(str[i])) {
if(positive && result > INT_MAX / 10) {
return INT_MAX;
}
if(positive && result == INT_MAX / 10 && int(str[i] - '0') >= 7) {
return INT_MAX;
}
if(!positive && -result < INT_MIN / 10) {
return INT_MIN;
}
if(!positive && -result == INT_MIN / 10 && int(str[i] - '0') >= 8) {
return INT_MIN;
}
result = result * 10 + int(str[i++] - '0');
}
if(!positive) result = -result;
return result;
}
};