-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathsolution.cpp
More file actions
40 lines (33 loc) · 928 Bytes
/
Copy pathsolution.cpp
File metadata and controls
40 lines (33 loc) · 928 Bytes
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 n = s.size();
int i = 0;
// Skip leading spaces
while (i < n && s[i] == ' ') {
i++;
}
// Check sign
int sign = 1;
if (i < n && (s[i] == '+' || s[i] == '-')) {
if (s[i] == '-') {
sign = -1;
}
i++;
}
long long num = 0;
int INT_MAX_VAL = 2147483647;
int INT_MIN_VAL = -2147483648;
// Read digits
while (i < n && isdigit(s[i])) {
int digit = s[i] - '0';
// Check overflow before adding digit
if (num > (INT_MAX_VAL - digit) / 10) {
return (sign == 1) ? INT_MAX_VAL : INT_MIN_VAL;
}
num = num * 10 + digit;
i++;
}
return (int)(sign * num);
}
};