-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathEvaluatePrefix.java
More file actions
51 lines (44 loc) · 1.5 KB
/
Copy pathEvaluatePrefix.java
File metadata and controls
51 lines (44 loc) · 1.5 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
import java.util.*;
public class EvaluatePrefix {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter PreFix :");
String Prefix = sc.nextLine();
Stack<Integer> sta = new Stack<>();
String rev = "";
for (int i = Prefix.length() - 1; i >= 0; i--) {
char ch = Prefix.charAt(i);
rev += ch;
}
System.out.print("Reverse Prefix :" + rev);
for (int i = 0; i < rev.length(); i++) {
char next = rev.charAt(i);
if (next >= 48 && next <= 57) {
sta.push(Integer.parseInt(next + ""));
} else {
int ope2 = sta.pop();
int ope1 = sta.pop();
switch (next) {
case '+':
sta.push(ope1 + ope2);
break;
case '-':
sta.push(ope2 - ope1);
break;
case '*':
sta.push(ope1 * ope2);
break;
case '/':
sta.push(ope2 / ope1);
break;
case '^':
sta.push((int) Math.pow(ope2, ope1));
break;
}
}
System.out.println("Final Answer :" + sta);
}
System.out.println("Popped Answer :" + sta.pop());
sc.close();
}
}