-
Notifications
You must be signed in to change notification settings - Fork 0
/
myAtoi.cc
35 lines (29 loc) · 864 Bytes
/
myAtoi.cc
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
// LeetCode: 8. String to Integer (atoi) (Medium)
class Solution {
public:
int myAtoi(string input) {
int sign = 1;
int result = 0;
int index = 0;
int n = input.size();
while (index < n && input[index] == ' ') {
index++;
}
if (index < n && input[index] == '+') {
sign = 1;
index++;
} else if (index < n && input[index] == '-') {
sign = -1;
index++;
}
while (index < n && isdigit(input[index])) {
int digit = input[index] - '0';
if ((result > INT_MAX / 10) || (result == INT_MAX / 10 && digit > INT_MAX % 10)) {
return sign == 1 ? INT_MAX : INT_MIN;
}
result = 10 * result + digit;
index++;
}
return sign * result;
}
};