算法 |《剑指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;
        }
}
}

猜你喜欢

转载自blog.csdn.net/CYK5201995/article/details/106535984