逆波兰逻辑运算java
时间: 2023-11-18 16:54:51 浏览: 40
逆波兰表达式是一种不含括号的表达式表示方法,它将运算符放在操作数的后面,因此也被称为后缀表达式。逆波兰表达式的计算可以通过栈来实现。在Java中,可以使用Stack类来实现栈的功能。具体实现过程可以分为以下几个步骤:
1. 将中缀表达式转换为后缀表达式(逆波兰表达式)。
2. 将后缀表达式中的操作数和运算符依次入栈。
3. 遇到运算符时,从栈中弹出两个操作数进行计算,并将计算结果入栈。
4. 最终栈中只剩下一个元素,即为逆波兰表达式的计算结果。
在实现过程中,需要注意输入四则运算的合法性判断,可以使用正则表达式字符匹配来实现。同时,也可以自己实现栈的功能,不一定需要使用Java类集。
相关问题
逆波兰表达式计算器java
以下是逆波兰表达式计算器的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();
}
}
```
逆波兰表达式java
逆波兰表达式是一种将运算符放在操作数后面的表达式,也被称为后缀表达式。在计算机科学中,逆波兰表达式通常比中缀表达式更容易计算和解析。下面是一个简单的逆波兰表达式的例子:
3 4 + 5 *
这个表达式的意思是:先将 3 和 4 相加,然后将结果乘以 5。使用栈可以很容易地计算逆波兰表达式。
Java代码实现:
```java
import java.util.Stack;
public class RPN {
public static int evalRPN(String[] tokens) {
Stack<Integer> stack = new Stack<>();
for (String token : tokens) {
if (token.equals("+")) {
stack.push(stack.pop() + stack.pop());
} else if (token.equals("-")) {
int b = stack.pop();
int a = stack.pop();
stack.push(a - b);
} else if (token.equals("*")) {
stack.push(stack.pop() * stack.pop());
} else if (token.equals("/")) {
int b = stack.pop();
int a = stack.pop();
stack.push(a / b);
} else {
stack.push(Integer.parseInt(token));
}
}
return stack.pop();
}
public static void main(String[] args) {
String[] tokens = {"3", "4", "+", "5", "*"};
System.out.println(evalRPN(tokens)); // 输出 35
}
}
```