forked from anitaa1990/Android-Cheat-sheet
-
Notifications
You must be signed in to change notification settings - Fork 0
/
NumberValidity.java
88 lines (70 loc) · 1.94 KB
/
NumberValidity.java
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
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
package math;
public class NumberValidity {
/*
* Given an input string, determine if it makes a valid number or not
*
* Eg: 4.325 is a valid number.
* 1.1.1 is NOT a valid number.
* 222 is a valid number.
* 22. is a valid number.
* 22.22. is NOT a valid number
*
* Runtime Complexity:
* Linear, O(n)
*
* Memory Complexity:
* Constant, O(1)
*
*
* */
enum STATE {START, INTEGER, DECIMAL, UNKNOWN}
;
private static STATE getNextState(STATE current_state,
char ch) {
switch (current_state) {
case START:
case INTEGER:
if (ch == '.') {
return STATE.DECIMAL;
} else if (ch >= '0' && ch <= '9') {
return STATE.INTEGER;
} else {
return STATE.UNKNOWN;
}
case DECIMAL:
if (ch >= '0' && ch <= '9') {
return STATE.DECIMAL;
} else {
return STATE.UNKNOWN;
}
}
return STATE.UNKNOWN;
}
static boolean isNumberValid(String s) {
if (s.isEmpty()) {
return true;
}
int i = 0;
if (s.charAt(i) == '+' || s.charAt(i) == '-') {
++i;
}
STATE current_state = STATE.START;
while (i < s.length()) {
current_state = getNextState(current_state, s.charAt(i));
if (current_state == STATE.UNKNOWN) {
return false;
}
i = i + 1;
}
return true;
}
public static void main(String[] args) {
String s = "4.325";
boolean isValid = isNumberValid(s);
if (isValid) {
System.out.println(s + " is valid.");
} else {
System.out.println(s + " is not valid.");
}
}
}