-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPostfixEvaluation.java
More file actions
49 lines (44 loc) · 1.49 KB
/
PostfixEvaluation.java
File metadata and controls
49 lines (44 loc) · 1.49 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
// solve postfix expression
import java.util.*;
public class PostfixEvaluation {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter postfix expression (e.g., 2 3 1 * + 9 -): ");
String postfix = sc.nextLine();
int result = evaluatePostfix(postfix);
System.out.println("Result = " + result);
}
public static int evaluatePostfix(String expr) {
Stack<Integer> stack = new Stack<>();
String[] tokens = expr.split("\\s+");
for (String token : tokens) {
if (isNumber(token)) {
stack.push(Integer.parseInt(token));
}
else {
int b = stack.pop();
int a = stack.pop();
int result = applyOperation(a, b, token.charAt(0));
stack.push(result);
}
}
return stack.pop();
}
public static boolean isNumber(String token) {
try {
Integer.parseInt(token);
return true;
} catch (Exception e) {
return false;
}
}
public static int applyOperation(int a, int b, char op) {
switch (op) {
case '+': return a + b;
case '-': return a - b;
case '*': return a * b;
case '/': return a / b;
default: throw new IllegalArgumentException("Invalid operator: " + op);
}
}
}