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 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68
| class Solution { public boolean isNumber(String s) { int i = 0, j = s.length() - 1;
while (i < j && s.charAt(i) == ' ') { i++; } while (i < j && s.charAt(j) == ' ') { j--; }
char c = s.charAt(i); if (c == ' ') { return false; } if (c == '+' || c == '-') { i++; }
boolean hasDot = false, hasNum = false; for (int k = i; k <= j; k++) { c = s.charAt(k); if (c == '.') { if (!hasDot) { hasDot = true; } else { return false; } } else if (c >= '0' && c <= '9') { hasNum = true; } else if (c == 'e' || c == 'E') { return hasNum && isInteger(s, k + 1, j); } else { return false; } }
return hasNum; }
private boolean isInteger(String s, int i, int j) { if (i > j) { return false; }
char c = s.charAt(i); if (c == '+' || c == '-') { i++; }
if (i > j) { return false; }
for (int k = i; k <= j; k++) { c = s.charAt(k); if (c < '0' || c > '9') { return false; } }
return true; } }
|