-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathvalid-number.java
More file actions
29 lines (25 loc) · 840 Bytes
/
Copy pathvalid-number.java
File metadata and controls
29 lines (25 loc) · 840 Bytes
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
class Solution {
public boolean isNumber(String s) {
s = s.trim();
if (s.isEmpty()) return false;
boolean num = false, dot = false, exp = false;
for (int i = 0; i < s.length(); i++) {
char c = s.charAt(i);
if (Character.isDigit(c)) num = true;
else if (c == '+' || c == '-') {
if (i > 0 && s.charAt(i - 1) != 'e' && s.charAt(i - 1) != 'E') return false;
}
else if (c == '.') {
if (dot || exp) return false;
dot = true;
}
else if (c == 'e' || c == 'E') {
if (exp || !num) return false;
exp = true;
num = false; // reset for exponent part
}
else return false;
}
return num;
}
}