-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMyAtoi.java
More file actions
51 lines (43 loc) · 1.13 KB
/
MyAtoi.java
File metadata and controls
51 lines (43 loc) · 1.13 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
/**
* 8 字符串转换整数
*/
public class MyAtoi {
public int myAtoi(String s) {
int res = 0;
int sign = 1;
s = s.trim();
int index = 0;
while (index<s.length()){
if(s.charAt(index)==' '){
index++;
}else{
break;
}
}
if(index==s.length()){
return res;
}
// 判断符号
if(s.charAt(index)=='-'){
sign = -1;
index++;
}else if(s.charAt(index)=='+'){
index++;
}
while (index<s.length()) {
int t = s.charAt(index)-'0';
// 不在0-9范围
if(t>9 || t<0){
break;
}
if(res>Integer.MAX_VALUE/10 || (res==Integer.MAX_VALUE/10 && t>Integer.MAX_VALUE%10)){
return Integer.MAX_VALUE;
}else if(res<Integer.MIN_VALUE/10 || (res==Integer.MIN_VALUE/10) && -t<Integer.MIN_VALUE%10){
return Integer.MIN_VALUE;
}
res = res*10 + sign*t;
index++;
}
return res;
}
}