逆波兰表达式计算器java
时间: 2023-12-20 16:32:04 浏览: 131
逆波兰式计算,将格式化数组转化为逆波兰表达式,a为输入的数组,n为其长度,p为输出逆波兰表达式的目标
以下是逆波兰表达式计算器的Java示例:
```java
import java.util.Stack;
public class EvaluateReversePolishNotation {
public int evalRPN(String[] tokens) {
Stack<Integer> stack = new Stack<>();
for (String token : tokens) {
if (token.equals("+")) {
int operand2 = stack.pop();
int operand1 = stack.pop();
stack.push(operand1 + operand2);
} else if (token.equals("-")) {
int operand2 = stack.pop();
int operand1 = stack.pop();
stack.push(operand1 - operand2);
} else if (token.equals("*")) {
int operand2 = stack.pop();
int operand1 = stack.pop();
stack.push(operand1 * operand2);
} else if (token.equals("/")) {
int operand2 = stack.pop();
int operand1 = stack.pop();
stack.push(operand1 / operand2);
} else {
stack.push(Integer.parseInt(token));
}
}
return stack.pop();
}
}
```
阅读全文