// 题目描述
// 将一个字符串转换成一个整数,要求不能使用字符串转换整数的库函数。 数值为0或者字符串不是一个合法的数值则返回0
// 输入描述:
// 输入一个字符串,包括数字字母符号,可以为空
// 输出描述:
// 如果是合法的数值表达则返回该数字,否则返回0
// 输入
//+2147483647
// 1a33
// 输出
//2147483647
// 0
public static int StrToInt(String str) {
if (str.length()<=0||str==null){
return 0;
}
char[] chars = str.toCharArray();
boolean isP = true;
int result = 0;
if (chars[0]=='-'){
isP = false;
}
for (int i=0;i<chars.length;i++){
if (i==0&&!isP||i==0&&chars[0]=='+'){
continue;
}
if (!(chars[i]>='0'&&chars[i]<='9')){
return 0;
}
result = result*10+charToInt(chars[i]);
}
if (isP){
return result;
}else {
return -result;
}
}
public static int charToInt(char ch){
switch (ch){
case '0': return 0;
case '1': return 1;
case '2': return 2;
case '3': return 3;
case '4': return 4;
case '5': return 5;
case '6': return 6;
case '7': return 7;
case '8': return 8;
case '9': return 9;
}
return 0;
}