-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpostFixEvaluation.java
More file actions
49 lines (42 loc) · 1.09 KB
/
postFixEvaluation.java
File metadata and controls
49 lines (42 loc) · 1.09 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
package Stacks;
import java.util.Stack;
/**
* postFix : val + val + operator
* Travel in forward direction only.
*/
public class postFixEvaluation {
private static int perform(char ch, int v1, int v2) {
switch (ch) {
case '-' -> {
return v1 - v2;
}
case '+' -> {
return v1 + v2;
}
case '*' -> {
return v1 * v2;
}
case '/' -> {
return v1 / v2;
}
default -> {
return -1;
}
}
}
public static void main(String[] args) {
String str = "953+4*6/-";
Stack<Integer> val = new Stack<>();
for (int i = 0; i < str.length(); i++) {
char ch = str.charAt(i);
if ((int) ch >= 48 && (int) ch <= 57)
val.push((int) ch - 48);
else {
int v2 = val.pop();
int v1 = val.pop();
val.push(perform(ch, v1, v2));
}
}
System.out.println(val.peek());
}
}