-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathSolution.java
More file actions
51 lines (39 loc) · 1.14 KB
/
Copy pathSolution.java
File metadata and controls
51 lines (39 loc) · 1.14 KB
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
50
51
class Solution {
public int myAtoi(String s) {
char[] arr = s.toCharArray();
int start = 0;
while (start < arr.length && arr[start] == ' ') {
start++;
}
int res = 0;
boolean isNeg = false;
int cutOff = Integer.MAX_VALUE / 10;
for (int i = start; i < arr.length; i++) {
char ch = arr[i];
if ((ch == '+' || ch == '-') && i == start) {
isNeg = ch == '-';
continue;
}
if (!isDigit(ch)) {
break;
}
int d = ch - '0';
if (res > cutOff) {
return isNeg ? Integer.MIN_VALUE : Integer.MAX_VALUE;
}
if (res == cutOff) {
if (isNeg && d >= 8) {
return Integer.MIN_VALUE;
}
if (!isNeg && d >= 7) {
return Integer.MAX_VALUE;
}
}
res = res * 10 + d;
}
return isNeg ? -1 * res : res;
}
private boolean isDigit(char ch) {
return ch >= '0' && ch <= '9';
}
}