[Sword Finger OFFER] Interview Question 20. A string representing a numeric value

Question : Please implement a function to determine whether a string represents a value (including integers and decimals). For example, the character strings "+100", "5e2", "-123", "3.1416", "0123" and "-1E-16" all represent numerical values, but "12e", "1a3.14", "1.2. 3", "±5" and "12e+5.4" are not.

Answer :

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;
		}
    }
}

Guess you like

Origin blog.csdn.net/weixin_44485744/article/details/105507683