/**
* 把字符串转换成整数
*
* 将一个字符串转换成一个整数,要求不能使用字符串转换整数的库函数。 数值为0或者字符串不是一个合法的数值则返回0
*
* 输入描述: 输入一个字符串,包括数字字母符号,可以为空
*
* 返回值描述: 如果是合法的数值表达则返回该数字,否则返回0
*
* 示例1
* 输入
* +2147483647
* 1a33
*
* 返回值
* 2147483647
* 0
*
*/
public class JZ049StrToInt {
public static int StrToInt(String str) {
if(str == null || str.length() <= 0) {
return 0;
}
int symble = 1;
char[] cs = str.toCharArray();
int sum = 0;
if (cs[0] == '-') {
symble = -1;
cs[0] = '0';
} else if (cs[0] == '+') {
cs[0] = '0';
}
for (char c : cs) {
if (c < '0' || c > '9') {
return 0;
} else {
sum = sum * 10 + (c - '0');
}
}
return sum * symble;
}
public static void main(String[] args) {
String str = "+2147483647";
System.out.println(StrToInt(str));
}
}