-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSolution.java
40 lines (39 loc) · 1.17 KB
/
Solution.java
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 str) {
int i = 0;
boolean positive = true;
while(i < str.length()) {
char c = str.charAt(i);
i++;
if (c != ' ') {
if (c == '-') {
positive = false;
} else if (c == '+') {
} else if (c <= '9' && c >= '0') {
i--;
} else {
return 0;
}
break;
}
}
int val = 0;
int detectLine = Integer.MIN_VALUE / 10 + 1;
while (i < str.length()) {
char c = str.charAt(i);
i++;
if (c >= '0' && c <= '9') {
int num = c - '0';
if (val < detectLine && (Integer.MIN_VALUE + num) / 10 > val) { // 越界检测
val = Integer.MIN_VALUE;
break;
}
val = val * 10 - num;
} else {
break;
}
}
// 需进行正数越界回归
return positive ? val == Integer.MIN_VALUE ? Integer.MAX_VALUE : -val : val;
}
}