forked from prayjourney/algorithm-in-java
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathIsNumber.java
More file actions
59 lines (53 loc) · 1.74 KB
/
IsNumber.java
File metadata and controls
59 lines (53 loc) · 1.74 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
public class IsNumber {
public static void main(String[] args){
String s1 = "abc";
String s2 = "-1.2";
String s3 = "1e-2";
String s4 = "0+01";
String s5 = " 1.2 ";
System.out.println(s1 + " " + isNumber(s1));
System.out.println(s2 + " " + isNumber(s2));
System.out.println(s3 + " " + isNumber(s3));
System.out.println(s4 + " " + isNumber(s4));
System.out.println(s5 + " " + isNumber(s5));
}
public static boolean isNumber(String s){
boolean num = false;
boolean exp = false;
boolean dot = false;
boolean space = false;
int N = s.length();
int i = 0;
while(i < N){
if(s.charAt(i) == ' ')
space = true;
else if(space)
return false; // no space for a number
else if(s.charAt(i) == '-' || s.charAt(i) == '+'){
// +/- should be after e
if (i > 0)
if (s.charAt(i-1) != 'e' && s.charAt(i-1) != 'E')
return false;
// i == 0 true if num == true
}
else if (s.charAt(i) >= '0' && s.charAt(i) <= '9')
num = true;
else if(s.charAt(i) == 'e' || s.charAt(i) == 'E'){
// only one e, at least one num in the front
if (exp || !num)
return false;
exp = true;
}
else if (s.charAt(i) == '.'){
// no e if dot, only one dot
if(exp || dot)
return false;
dot = true;
}
else
return false;
i++;
}
return num;
}
}