public class Solution {

public int myAtoi(String str) {

```
if(str==null || str.length()<=0) return 0;
int res=0;
int index=0;
while((index<str.length()) && (str.charAt(index)==' ')){
index++; //find the first non-whitespace
}
int sign=0; //the count of signal.
boolean isNegative=false; //the negative signal
for(;index<str.length() && (sign<2);index++){
char ch=str.charAt(index);
int val=ch-48;
if((ch=='+' || ch=='-')){
sign++;
if(ch=='-') isNegative=true;
continue;
}
if((val>9 || val<0)) //if there is other char , it it illegal.
break;
if(!isNegative && res>(Integer.MAX_VALUE-val)/10)
return Integer.MAX_VALUE;
if(isNegative && ( res> (Integer.MAX_VALUE-val)/10))
return Integer.MIN_VALUE;
res=10*res+val; //the result of number
}
if(isNegative)
return res*-1;
return res;
}
```

}