-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathAtoI.java
More file actions
46 lines (40 loc) · 1.16 KB
/
Copy pathAtoI.java
File metadata and controls
46 lines (40 loc) · 1.16 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
public class AtoI {
static int ConvertAtoI(String s){
int n = s.length();
int r = 0;
int sign =1;
int index =0;
//Spaces
while(index<n && s.charAt(index) == ' '){
index++;
}
//Sign
if(index<n && s.charAt(index) =='-' ){
sign = -1;
index++;
}
else{
if(index<n && s.charAt(index) == '+'){
sign = 1;
index++;
}
}
while(index<n && Character.isDigit(s.charAt(index))){
int digit = s.charAt(index) - '0';
if(r>=Integer.MAX_VALUE/10 || (r==Integer.MAX_VALUE/10 && digit > Integer.MAX_VALUE %10)){
return sign == 1 ?Integer.MAX_VALUE : Integer.MIN_VALUE;
}
else{
if(r<= Integer.MIN_VALUE /10 ){
return Integer.MIN_VALUE;
}
}
r = r*10+digit;
index++;
}
return r * sign;
}
public static void main(String[] args) {
System.out.println(ConvertAtoI("-9568"));
}
}