题目描述
将一个字符串转换成一个整数,要求不能使用字符串转换整数的库函数。 数值为0或者字符串不是一个合法的数值则返回0
输入描述:
输入一个字符串,包括数字字母符号,可以为空
输出描述:
如果是合法的数值表达则返回该数字,否则返回0
输入例子:
+2147483647 1a33
输出例子:
2147483647 0
算法解析: 对于正确的数字形式为,123, +123, -123,对于这种形式的数字字符串,我们需要注意的是排除一些错误的形式,比如21+, +, 23e4,然后从后往前计算就好。 代码如下:
static int mState = 0; public static final int NORMAL = 0; public static final int EMPTY_POINT = 1; public static final int EMPTY_STRING = 2; public static final int ERROR = 3; public static int StrToInt(String str) { if (str == null) { mState = EMPTY_POINT; return 0; } else if (str.length() <= 0) { mState = EMPTY_STRING; return 0; } else if ((str.length() == 1) && (str.charAt(0) == '+' || str.charAt(0) == '-')) { mState = ERROR; return 0; } int result = 0; int temp = 1; for (int i = str.length() - 1; i >= 0; i--) { char c = str.charAt(i); if (c >= '0' && c <= '9') { result += (c - '0') * temp; temp *= 10; } else if (c == '+' && i == 0) { return result; } else if (c == '-' && i == 0) { return -result; } else { mState = ERROR; return 0; } } return result; }新闻热点
疑难解答