-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path8.cpp
More file actions
27 lines (23 loc) · 767 Bytes
/
8.cpp
File metadata and controls
27 lines (23 loc) · 767 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
class Solution {
public:
int myAtoi(string s){
int i = 0; int n = s.length();
while(i < n && s[i] == ' ') i++;
bool neg = false;
if(i < n && s[i] == '-'){neg = true; i++;}
else if(i < n && s[i] == '+') i++;
int m = neg ? -1 : 1;
int result = 0;
while(i < n && s[i]-'0' >= 0 && s[i]-'0' < 10){
if(result > INT_MAX/10) return INT_MAX;
if(result < INT_MIN/10) return INT_MIN;
result *= 10;
int d = m*(s[i] - '0');
if(result > INT_MAX - abs(d)) return INT_MAX;
if(result < INT_MIN + abs(d)) return INT_MIN;
result += d;
i++;
}
return result;
}
};