forked from examplehub/Java
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPostfixEvaluation.java
More file actions
41 lines (39 loc) · 1.14 KB
/
PostfixEvaluation.java
File metadata and controls
41 lines (39 loc) · 1.14 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
package com.examplehub.datastructures.stack;
import java.util.Stack;
public class PostfixEvaluation {
/**
* Postfix expression evaluation.
*
* @param postfix the postfix to be evaluated.
* @return result of postfix expression.
*/
public static int evaluate(String postfix) {
Stack<Integer> result = new Stack<>();
for (int i = 0; i < postfix.length(); ++i) {
if (Character.isDigit(postfix.charAt(i))) {
result.push(Integer.valueOf("" + postfix.charAt(i)));
} else {
int secondNumber = result.pop();
int firstNumber = result.pop();
switch (postfix.charAt(i)) {
case '+':
result.push(firstNumber + secondNumber);
break;
case '-':
result.push(firstNumber - secondNumber);
break;
case '*':
result.push(firstNumber * secondNumber);
break;
case '/':
result.push(firstNumber / secondNumber);
break;
case '^':
result.push((int) Math.pow(firstNumber, secondNumber));
break;
}
}
}
return result.pop();
}
}