后缀表达式求值java
时间: 2023-11-18 17:54:09 浏览: 44
后缀表达式求值是一种常见的算法,也被称为逆波兰表达式求值。它的基本思想是使用栈来存储操作数,遇到操作符时弹出栈顶的两个操作数进行计算,并将计算结果压入栈中。最终,栈中只剩下一个元素,即为表达式的计算结果。下面是后缀表达式求值的java代码实现:
```
public int evaluatePostfix(String[] tokens) {
Stack<Integer> stack = new Stack<>();
for (String token : tokens) {
if (isNumber(token)) {
stack.push(Integer.parseInt(token));
} else {
int operand2 = stack.pop();
int operand1 = stack.pop();
int result = evaluate(operand1, operand2, token);
stack.push(result);
}
}
return stack.pop();
}
private boolean isNumber(String token) {
return token.matches("\\d+");
}
private int evaluate(int operand1, int operand2, String operator) {
switch (operator) {
case "+":
return operand1 + operand2;
case "-":
return operand1 - operand2;
case "*":
return operand1 * operand2;
case "/":
return operand1 / operand2;
default:
throw new IllegalArgumentException("Invalid operator: " + operator);
}
}
```
其中,`tokens`是后缀表达式的字符串数组,`isNumber`方法用于判断一个字符串是否为数字,`evaluate`方法用于计算两个操作数和一个操作符的结果。
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![doc](https://img-home.csdnimg.cn/images/20210720083327.png)