-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathValid Number
53 lines (52 loc) · 1.66 KB
/
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
/*
*Validate if a given string is numeric.
*Some examples:
*v"0" => true
*" 0.1 " => true
*"abc" => false
*"1 a" => false
*v"2e10" => true
*Note: It is intended for the problem statement to be ambiguous. You should gather all requirements up front before implementing one.
*
*Update (2015-02-10):
*The signature of the C++ function had been updated. If you still see your function signature accepts a const char * argument, please click the reload button to reset your code definition.
*/
public class Solution {
public boolean isNumber(String s) {
if (s == null || s.trim().length() == 0) {
return false;
}
s = s.trim();
int i = 0;
if (s.charAt(i) == '+' || s.charAt(i) == '-') {
i++;
}
boolean hasE = false;
boolean hasDot = false;
boolean hasNum = false;
for (; i < s.length(); i++) {
char c = s.charAt(i);
if (c == '.') {
if (hasDot || hasE) {
return false;
}
hasDot = true;
} else if(c == 'e' || c == 'E') {
if (hasE || !hasNum || i == s.length() - 1) {
return false;
}
hasE = true;
} else if(c == '+' || c == '-') {
if (i - 1 >= 0 && (s.charAt(i - 1) == 'e' || s.charAt(i - 1) == 'E') && i != s.length() - 1) {
continue;
}
return false;
} else if(Character.isDigit(s.charAt(i))) {
hasNum = true;
} else {
return false;
}
}
return hasNum;
}
}