用positive确定是正数还是负数,
每次累加时需要判断当前得到的值和最大/小值除以10的值
class Solution {
public int strToInt(String str) {
int len=str.length();
if(len==0) return 0;
int idx=0;
while(idx<len && str.charAt(idx)==' ') idx++;
int positive=1;
if(str.charAt(idx)=='-'||str.charAt(idx)=='+'){
if(str.charAt(idx)=='-')
positive=-1;
idx++;
}
int res=0;
while(idx<len && str.charAt(idx)>='0' && str.charAt(idx)<='9'){
if(positive==1){
if(res>Integer.MAX_VALUE/10) return Integer.MAX_VALUE;
}
if(positive==-1){
if(-res<Integer.MIN_VALUE/10) return Integer.MIN_VALUE;
}
res*=10;
res+=str.charAt(idx)-'0';
idx++;
}
return res*positive;
}
}