-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathReversePolishNotation.java
More file actions
46 lines (43 loc) · 1.18 KB
/
ReversePolishNotation.java
File metadata and controls
46 lines (43 loc) · 1.18 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
package array;
import java.util.Stack;
public class ReversePolishNotation {
public static int eval(String notation[]) {
Stack<String> stack = new Stack<String>();
String operator = "*/+";
int a, b;
for (int i = 0; i < notation.length; i++) {
if (operator.contains(notation[i])) {
// Its operation
switch (notation[i]) {
case "*":
a = Integer.parseInt(stack.pop());
b = Integer.parseInt(stack.pop());
stack.push(String.valueOf((a * b)));
break;
case "/":
a = Integer.parseInt(stack.pop());
b = Integer.parseInt(stack.pop());
stack.push(String.valueOf((a / b)));
break;
case "-":
a = Integer.parseInt(stack.pop());
b = Integer.parseInt(stack.pop());
stack.push(String.valueOf((a - b)));
break;
case "+":
a = Integer.parseInt(stack.pop());
b = Integer.parseInt(stack.pop());
stack.push(String.valueOf((a + b)));
break;
}
} else {
stack.push(notation[i]);
}
}
return Integer.parseInt(stack.pop());
}
public static void main(String args[]) {
String notation[] = { "2", "3", "+", "1", "*" };
System.out.println("Result of eveluated expression ::" + eval(notation));
}
}