【剑指OFFER】面试题20. 表示数值的字符串

题目:请实现一个函数用来判断字符串是否表示数值(包括整数和小数)。例如,字符串"+100"、“5e2”、"-123"、“3.1416”、“0123"及”-1E-16"都表示数值,但"12e"、“1a3.14”、“1.2.3”、"±5"及"12e+5.4"都不是。

解答

class Solution {
    
    
    public boolean isNumber(String s) {
    
    //利用异常来进行判断是否可以表示数值
        try {
    
    
            if(s.endsWith("f")||s.endsWith("d")||s.endsWith("F")||s.endsWith("D")){
    
    
                throw new NumberFormatException();
            }
			Float.parseFloat(s);
            return true;
		} catch (Exception e) {
    
    
			return false;
		}
    }
}

猜你喜欢

转载自blog.csdn.net/weixin_44485744/article/details/105507683