Valid Number
问题描述
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.
解决思路
类似于这样的问题,说难也难,说容易也容易。
难的地方在于很难一次写出freebug的代码,容易的地方在于枚举规则,仅此一条思路而已。
大致需要注意的思路如下:
1. s = s.trim();
2. + / - 开头出现,e后面也可以出现;
3. ‘.’的位置,注意题目中的".01"也是合法的;
4. ‘001.1’这样的是否合法?
程序
public boolean isNumber(String s) { if (s == null || s.trim().length() == 0) { return false; } s = s.trim(); int idx = 0; if (s.charAt(idx) == '+' || s.charAt(idx) == '-') { ++idx; } if (idx >= s.length()) { return false; } boolean hasDot = false; boolean hasE = false; int dotIdx = idx; int eIdx = idx; for (int i = idx; i < s.length(); i++) { char c = Character.toLowerCase(s.charAt(i)); if (c == '.') { if (hasDot || hasE) { return false; } hasDot = true; dotIdx = i; continue; } if (c == 'e') { if (hasE) { return false; } if (hasDot && i - 1 == idx && Character.toLowerCase(s.charAt(i - 1)) == '.') { // .e return false; } hasE = true; eIdx = i; continue; } if (hasE && Character.toLowerCase(s.charAt(i - 1)) == 'e' && i != s.length() - 1 && (s.charAt(i) == '-' || s.charAt(i) == '+')) { // 1e+ continue; } if (!Character.isDigit(c)) { // 'a''b'... return false; } } if (hasDot) { if (s.substring(dotIdx + 1).length() == 0 && s.substring(idx, dotIdx).length() == 0) { // '.' return false; } } if (hasE) { if (s.substring(eIdx + 1).length() == 0) { return false; } if (s.substring(idx, eIdx).length() == 0) { return false; } } return true; }
附上 Test Case
String[] s = { "0", " 0.1", "abc", "1 a", "2e10", "0.1e-10", ".01", "e10", "-1e-10", "1e", ".", "3.", ".e1", "4e+", "46.e3" };
Output
0 true
0.1 true
abc false
1 a false
2e10 true
0.1e-10 true
.01 true
e10 false
-1e-10 true
1e false
. false
3. true
.e1 false
4e+ false
46.e3 true