-
Notifications
You must be signed in to change notification settings - Fork 265
Expand file tree
/
Copy path73.java
More file actions
42 lines (40 loc) · 1.06 KB
/
73.java
File metadata and controls
42 lines (40 loc) · 1.06 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
class Solution {
public int strToInt(String str) {
str = str.trim();
if(str.equals("")){
return 0;
}
int n = str.length();
int p = 0;
char[] chs = str.toCharArray();
int res = 0;
int flag = 1;
if(chs[p]=='-'){
flag = -1;
p++;
}else if(chs[p]=='+'){
p++;
}
for(; p<n; p++){
char ch = chs[p];
if(ch>='0' && ch<='9'){
//溢出判断
if(flag==1){
//res * 10 + cur > max
if(res>(Integer.MAX_VALUE - (ch-'0'))/10){
return Integer.MAX_VALUE;
}
}else{
//-res * 10 - cur < min
if(-res<(Integer.MIN_VALUE + ch - '0')/10){
return Integer.MIN_VALUE;
}
}
res = res*10 + ch - '0';
}else{
break;
}
}
return res*flag;
}
}