和上一题 reverse integer 有类似之处,但还多了几个checking的地方:
1,trim leading and trailing whitespace, just use str.trim()
2,check the 1st letter.
3,check char type must be digit, there should be a function, but it is also easy to just write <'0' or >'9'
4,overflow,both MAX_VALUE and MIN_VALUE
效率80+%
public class Solution {
public int myAtoi(String str) {
if(str.length()==0) return 0;
String s=str.trim();
int len=s.length();
boolean isNeg=false;
int i=0;
if(s.charAt(i)=='-') isNeg=true;
int result=0;
int digit=0;
if(s.charAt(i)=='-'||s.charAt(i)=='+') i++;
while(i<len){
if(s.charAt(i)>'9' ||s.charAt(i)<'0' ) break;
digit = s.charAt(i)-'0';
if(isNeg && -result<(Integer.MIN_VALUE+digit)/10) return Integer.MIN_VALUE;
if(!isNeg && result>(Integer.MAX_VALUE-digit)/10) return Integer.MAX_VALUE;
result = result*10+digit;
++i;
}
return isNeg?-result:result;
}
}