題目
Validate if a given string is numeric.
Some examples:
"0" => true
" 0.1 " => true
"abc" => false
"1 a" => false
"2e10" => true
Note: It is intended for the problem statement to be ambiguous. You should gather all requirements up front before implementing one.
分析這題要考慮的情況很多,所以通過率不高。
這裡給出了兩種比較簡潔的寫法:
解法1:利用正則表達式。
解法2:直接利用java提供的parseDouble或parseFloat函數幫助判斷,這算是投機取巧的方法了,需要注意的是java類庫裡認為以“f”, "F", "d", "D"結尾的都是合法的,而LeetCode上都視為非法,需要特殊處理下。parseDouble和parseFloat具體的實現方法都是用的類庫中的FloatingDecimal.readJavaFormatString(s),源碼參見http://www.bvbcode.com/cn/joa60xtr-137004。
解法1
public class ValidNumber {
public boolean isNumber(String s) {
return s.trim().matches("[-+]?(\\d+\\.?|\\.\\d+)\\d*(e[-+]?\\d+)?");
}
}解法2
public class ValidNumber {
public boolean isNumber(String s) {
if (s.contains("f") || s.contains("f") || s.contains("d")
|| s.contains("D")) {
return false;
}
try {
Double.parseDouble(s);
} catch (Exception e) {
return false;
}
return true;
}
}