Poison

65. Valid Number

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
class Solution {
public boolean isNumber(String s) {
boolean hasDot = false, hasNumber = false;

// 注意符号位仅能出现在开头
for (int i = getNumStartIndex(s, 0); i < s.length(); i++) {
char c = s.charAt(i);
if (c == 'e' || c == 'E') {
if (!hasNumber) {
return false;
}

return isInt(s, i + 1);
} else if (c >= '0' && c <= '9') {
hasNumber = true;
} else if (c == '.') {
if (!hasDot) {
hasDot = true;
} else {
return false;
}
} else {
return false;
}
}

return hasNumber;
}

private int getNumStartIndex(String s, int i) {
if (i == s.length()) {
return i;
}

char c = s.charAt(i);
return c == '+' || c == '-' ? i + 1 : i;
}

private boolean isInt(String s, int i) {
i = getNumStartIndex(s, i);
if (i == s.length()) {
return false;
}

while (i < s.length()) {
char c = s.charAt(i);
if (c < '0' || c > '9') {
return false;
}
i++;
}

return true;
}
}
Reference

65. Valid Number