-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpreFixEvaluation.java
More file actions
50 lines (43 loc) · 1.13 KB
/
preFixEvaluation.java
File metadata and controls
50 lines (43 loc) · 1.13 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
package Stacks;
import java.util.Stack;
/**
* preFix : operator + val + val
* Travel in backward direction only.
* Also, v1 is first popped.
*/
public class preFixEvaluation {
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 = "-9/*+5346";
Stack<Integer> val = new Stack<>();
for (int i = str.length() - 1; i >= 0; i--) {
char ch = str.charAt(i);
if ((int) ch >= 48 && (int) ch <= 57)
val.push((int) ch - 48);
else {
int v1 = val.pop();
int v2 = val.pop();
val.push(perform(ch, v1, v2));
}
}
System.out.println(val.peek());
}
}