一,判断字符串转化成的int型变量是否溢出
这里指的是理想情况,即字符串中的字符只包含数字和±号
public int myAtoi(String str) {
int flag=1; //正负标记
int res=0;
int i=0;
if(str.charAt(i)=='-')
flag=-1;
if(str.charAt(i)=='-'||str.charAt(i)=='+')
i++;
while(i<str.length()){
int value=str.charAt(i)-'0'; //得到当前数字
//保证末尾数字小于或等于7才不会溢出
if(res>Integer.MAX_VALUE/10||res==Integer.MAX_VALUE/10&&value>7) {
return flag>0?Integer.MAX_VALUE:Integer.MIN_VALUE;
}
res=res*10+value;
i++;
}
return flag>0?res:-res;
}
(未完待续…)