forked from yubinbai/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSolution.java
More file actions
68 lines (65 loc) · 1.85 KB
/
Solution.java
File metadata and controls
68 lines (65 loc) · 1.85 KB
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
public class Solution {
public boolean isNumber(String s) {
char[] str = s.trim().toCharArray();
if (str.length == 0) return false;
boolean dotUsed = false;
boolean expUsed = false;
boolean hasPrimary = false;
boolean hasExponent = false;
int pos = 0;
if (str[0] == '+' || str[0] == '-') {
pos = 1;
}
for (; pos < str.length; pos++) {
char c = str[pos];
if (c == '+' || c == '-') {
return false;
} else if (c == '.') {
if (dotUsed || expUsed) {
return false;
} else {
dotUsed = true;
}
} else if (c == 'e' || c == 'E') {
if (expUsed) {
return false;
} else {
expUsed = true;
if (pos + 1 < str.length) {
if (str[pos + 1] == '+' || str[pos + 1] == '-') {
pos++;
}
}
}
} else if (c >= '0' && c <= '9') {
if (expUsed) {
hasExponent = true;
} else {
hasPrimary = true;
}
} else {
return false;
}
}
return hasPrimary && (expUsed == hasExponent);
}
public static void main(String[] args) {
Solution s = new Solution();
String[] tests = {
"-1.",
" ",
"6+1",
"0",
" 0.1 ",
"abc",
"1 a",
"2e10",
"2e1.0",
"e",
"000123e-2",
};
for (String str : tests) {
System.out.println(s.isNumber(str));
}
}
}