-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsti.java
More file actions
40 lines (38 loc) · 1.03 KB
/
sti.java
File metadata and controls
40 lines (38 loc) · 1.03 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
package StringtoInteger008;
/**
* Created by Administrator on 2017/8/13.
*/
public class sti {
public int myAtoi(String str){
if(str==null)
return 0;
str=str.trim();
if(str.length()==0)
return 0;
boolean isNeg=false;
int i=0;
if(str.charAt(0)=='-'||str.charAt(0)=='+'){
i++;
if(str.charAt(0)=='-')
isNeg=true;
}
int res=0;
while(i<str.length()){
if(str.charAt(i)<'0'||str.charAt(i)>'9')
break;
int digit=(int)(str.charAt(i)-'0');
if(isNeg&&res>-((Integer.MIN_VALUE+digit)/10))
return Integer.MIN_VALUE;
else if(!isNeg&&res>(Integer.MAX_VALUE-digit)/10)
return Integer.MAX_VALUE;
res=res*10+digit;
i++;
}
return isNeg?-res:res;
}
public static void main(String[] args){
String s="-1234";
int a=new sti().myAtoi(s);
System.out.print(a);
}
}