-
Notifications
You must be signed in to change notification settings - Fork 17
/
Copy pathInfixEvaluation.java
71 lines (55 loc) · 2 KB
/
InfixEvaluation.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
import java.util.*;
public class Main {
public static void main(String args[]) {
System.out.println(evaluate("2+(5-3*6/2)"));
}
static int evaluate(String str) {
Stack<Integer> operand = new Stack<>();
Stack<Character> operator = new Stack<>();
for(int i=0; i<str.length(); i++) {
char c = str.charAt(i);
if(c == '(') {
operator.push(c);
} else if(Character.isDigit(c)) {
operand.push(c - '0');
} else if(c == '+' || c == '-' || c == '*' || c == '/') {
while(!operator.isEmpty() && operator.peek() != '(' && precendence(operator.peek()) >= precendence(c)) {
int o2 = operand.pop();
int o1 = operand.pop();
char op = operator.pop();
operand.push(calculate(o1, o2, op));
}
operator.push(c);
} else if(c == ')') {
while(operator.peek() != '(') {
int o2 = operand.pop();
int o1 = operand.pop();
char op = operator.pop();
operand.push(calculate(o1, o2, op));
}
operator.pop();
}
}
while(!operator.isEmpty()) {
int o2 = operand.pop();
int o1 = operand.pop();
char op = operator.pop();
operand.push(calculate(o1, o2, op));
}
return operand.pop();
}
static int precendence(char operator) {
if(operator == '+') return 1;
else if(operator == '-') return 1;
else if(operator == '*') return 2;
else if(operator == '/') return 2;
return -1;
}
static int calculate(int o1, int o2, char operator) {
if(operator == '+') return o1+o2;
else if(operator == '-') return o1-o2;
else if(operator == '*') return o1*o2;
else if(operator == '/') return o1/o2;
return 0;
}
}