劍指offer22

題目描述

將一個字符串轉換成一個整數(實現Integer.valueOf(string)的功能,可是string不符合數字要求時返回0),要求不能使用字符串轉換整數的庫函數。 數值爲0或者字符串不是一個合法的數值則返回0。java

解題思路分析

這道題就是須要注意幾種狀況,很簡單函數

  • 首先首字符是不是表示符號位,由於跟最終的結果返回有很大的關係
  • 其次注意是否出現了非0-9的字符,出現了的話直接返回0
  • 最後記得正負判斷

代碼實現

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;
}
複製代碼
相關文章
相關標籤/搜索