1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42
| class Solution { public boolean isNumber(String s) { char[] cs = s.toCharArray(); int index = -1, n = cs.length; for (int i = 0; i < n; ++i) { if (cs[i] == 'e' || cs[i] == 'E') { if (index == -1) index = i; else return false; } } boolean ans = true; if (index == -1) { ans &= check(cs, 0, n - 1, false); } else { ans &= check(cs, 0, index - 1, false); ans &= check(cs, index + 1, n - 1, true); } return ans; }
private boolean check(char[] cs, int start, int end, boolean mustInteger) { if (start > end) return false; if (cs[start] == '+' || cs[start] == '-') ++start; boolean hasDot = false, hasNum = false; for (int i = start; i <= end; ++i) { if (cs[i] == '.') { if (hasDot || mustInteger) return false; hasDot = true; } else if (cs[i] >= '0' && cs[i] <= '9') { hasNum = true; } else { return false; } } return hasNum; } }
|