-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathEvaluatePostFix.java
More file actions
55 lines (52 loc) · 1.6 KB
/
EvaluatePostFix.java
File metadata and controls
55 lines (52 loc) · 1.6 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
52
53
54
55
package datastructure.stackandqueue.stack;
/**
* The type Evaluate post fix.
*/
public class EvaluatePostFix {
/**
* Evaluate int.
*
* @param expression the expression
* @return the int
*/
public static int evaluate(String expression) {
Stack<Integer> stack = new Stack<>(expression.length());
//1.Scan expression character by character,
//2.If character is a number push it in stack
//3.If character is operator then pop two elements from stack
//perform the operation and put the result back in stack
//At the end, Stack will contain result of whole expression.
for (int i = 0; i < expression.length(); i++) {
char c = expression.charAt(i);
if (!Character.isDigit(c)) {
Integer x = stack.pop();
Integer y = stack.pop();
switch (c) {
case '+':
stack.push(y + x);
break;
case '-':
stack.push(y - x);
break;
case '*':
stack.push(y * x);
break;
case '/':
stack.push(y / x);
break;
}
} else {
stack.push(Character.getNumericValue(c));
}
}
return stack.pop();
}
/**
* Main.
*
* @param args the args
*/
public static void main(String args[]) {
System.out.println(evaluate("921*-8-4+"));
}
}