題目描述
將一個字符串轉換成一個整數,要求不能使用字符串轉換整數的庫函數。 數值為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; }新聞熱點
疑難解答