算法 |《劍指offer》面試題20. 表示數值的字符串

請實現一個函數用來判斷字符串是否表示數值(包括整數和小數)。例如,字符串"+100"、“5e2”、"-123"、“3.1416”、“0123"都表示數值,但"12e”、“1a3.14”、“1.2.3”、“±5”、"-1E-16"及"12e+5.4"都不是。

題解:
class Solution {
    public boolean isNumber(String s) {
        //正則表達式的使用
        // s = s.trim();
        // if(s == null || s.length() == 0) return false;
        // while(s.length() > 0 && s.charAt(0) == ' ') 
        //     s = new StringBuilder(s).deleteCharAt(0).toString();
        // return s.matches("(([\\+\\-]?[0-9]+(\\.[0-9]*)?)|([\\+\\-]?\\.?[0-9]+))(e[\\+\\-]?[0-9]+)?");
        //利用函數和異常
        try{
            if(s.endsWith("f")||s.endsWith("d")||s.endsWith("F")||s.endsWith("D"))
            {
                throw new NumberFormatException();
            }
            double d = Double.parseDouble(s);
            return true;
        }catch(Exception e)
        {
            return false;
        }
}
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章