-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathParseExpression.java
More file actions
96 lines (81 loc) · 2.79 KB
/
ParseExpression.java
File metadata and controls
96 lines (81 loc) · 2.79 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
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
package fourEqualsTen;
import java.util.ArrayList;
import java.util.List;
import java.util.Stack;
public class ParseExpression {
public static float evaluateExpression(String expression) {
Stack<Float> values = new Stack<>();
Stack<Character> operators = new Stack<>();
for (int i = 0; i < expression.length(); i++) {
char c = expression.charAt(i);
if (Character.isDigit(c)) {
StringBuilder num = new StringBuilder();
while (i < expression.length() && (Character.isDigit(expression.charAt(i)) || expression.charAt(i) == '.')) {
num.append(expression.charAt(i));
i++;
}
i--;
values.push(Float.parseFloat(num.toString()));
} else if (c == '(') {
operators.push(c);
} else if (c == ')') {
while (!operators.isEmpty() && operators.peek() != '(') {
values.push(applyOperator(operators.pop(), values.pop(), values.pop()));
}
operators.pop(); // Pop the '('
} else if (isOperator(c)) {
while (!operators.isEmpty() && precedence(c) <= precedence(operators.peek())) {
values.push(applyOperator(operators.pop(), values.pop(), values.pop()));
}
operators.push(c);
}
}
while (!operators.isEmpty()) {
values.push(applyOperator(operators.pop(), values.pop(), values.pop()));
}
return values.pop();
}
private static boolean isOperator(char c) {
return c == '+' || c == '-' || c == '*' || c == '/';
}
private static int precedence(char operator) {
switch (operator) {
case '+':
case '-':
return 1;
case '*':
case '/':
return 2;
}
return -1;
}
private static float applyOperator(char operator, float b, float a) {
if (operator == '/' && b == 0) {
return -1;
}
switch (operator) {
case '+':
return a + b;
case '-':
return a - b;
case '*':
return a * b;
case '/':
return a / b;
}
return 0;
}
public static List<String> evaluateExpressionResult(List<String> expressions)
{
List<String> res = new ArrayList<>();
for (String expr: expressions)
{
float f = evaluateExpression(expr);
if (f == 10)
{
res.add(expr);
}
}
return res;
}
}