public int StrToInt(String str) {
if(str==null || str.length()==0){
return 0;
}
//判断是否是负数
boolean isNegative = str.charAt(0)=='-';
int res=0;
for(int i=0;i<str.length();i++){
char ch = str.charAt(i);
if(i==0 && (ch=='+' || ch=='-')){ //第一位有可能是符号位
continue;
}
if(ch<'0' || ch>'9'){ //字符不是数字
return 0;
}
res = res*10+(ch-'0');
}
//注意:当 str = "-2147483648" 时,res = 2147483640 + 8 = -2147483648
//由于 int 范围限制,则 -(-2147483648) = -2147483648
return isNegative?-res:res;
}
www.mianshi.online,www.i9code.cn
本文由博客一文多发平台 OpenWrite 发布!