將一個字符串轉換成一個整數(實現Integer.valueOf(string)的功能,可是string不符合數字要求時返回0),要求不能使用字符串轉換整數的庫函數。 數值爲0或者字符串不是一個合法的數值則返回0。java
這道題就是須要注意幾種狀況,很簡單函數
public int strToInt(String str) {
if (str == null || str.length() <= 0) {
return 0;
}
int length = str.length();
int s = 1, result = 0;
//第一個字符爲''-'的話則爲負數
if (str.charAt(0) == '-') {
s = -1;
}
//經過判斷第一個字符來判斷從第幾個字符開始遍歷
for (int i = (str.charAt(0) == '-' || str.charAt(0) == '+') ? 1 : 0; i < length; i++) {
if (str.charAt(i) < '0' || str.charAt(i) > '9') {
return 0;
}
result = result * 10 + str.charAt(i) - '0';
}
return result *= s;
}
複製代碼