-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path8.java
More file actions
17 lines (17 loc) · 704 Bytes
/
8.java
File metadata and controls
17 lines (17 loc) · 704 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
public class Solution {
public int myAtoi(String str) {
if (str.isEmpty()) return 0;
int sign = 1, base = 0, i = 0, n = str.length();
while (i < n && str.charAt(i) == ' ') ++i;
if (str.charAt(i) == '+' || str.charAt(i) == '-') {
sign = (str.charAt(i++) == '+') ? 1 : -1;
}
while (i < n && str.charAt(i) >= '0' && str.charAt(i) <= '9') {
if (base > Integer.MAX_VALUE / 10 || (base == Integer.MAX_VALUE / 10 && str.charAt(i) - '0' > 7)) {
return (sign == 1) ? Integer.MAX_VALUE : Integer.MIN_VALUE;
}
base = 10 * base + (str.charAt(i++) - '0');
}
return base * sign;
}
}