将一个字符串转换成一个整数,要求不能使用字符串转换整数的库函数。 数值为0或者字符串不是一个合法的数值则返回0
避开几个雷区就很简单了 1.字符串为null或者"" 返回0 2.字符串表示值超过int范围 返回0
//输入一个字符串,包括数字字母符号,可以为空
//输出描述:
//如果是合法的数值表达则返回该数字,否则返回 0
public int StrToInt(String str) {
if (str==null||str.length()==0){
return 0;
}
int sign=1;
long res=0;
if (str.charAt(0)=='+'||str.charAt(0)=='-'){//首位判断
sign=str.charAt(0)=='+'?1:-1;
int j=1;
while (j<str.length()){
if (str.charAt(j)>48&&str.charAt(j)<=57){
res=res*10+(str.charAt(j)-48);
j++;
}else {
return 0;
}
}
}else if (str.charAt(0)>48&&str.charAt(0)<=57){//0的acsii码十进制为48 9为57
res=str.charAt(0)-48;
int i=1;
while (i<str.length()){
if (str.charAt(i)>48&&str.charAt(i)<=57){
res=res*10+str.charAt(i)-48;
i++;
}else {
return 0;
}
}
}
if (sign==-1){
res=-res;
}
if(res>Integer.MAX_VALUE||res<Integer.MIN_VALUE){
return 0;
}else {
return Integer.parseInt(res+"");
}
// return sign*res;
}