Home >Java >javaTutorial >Example of reverse Polish expression implementation in Java
This article mainly introduces the relevant content of the reverse Polish expression of the Java algorithm. The definition of the reverse Polish expression has been implemented in Java. It has certain reference value. Friends who need it can learn about it.
Reverse Polish expression
Definition: The traditional four arithmetic operations are called infix expressions, that is, the operator is actually between the two operands. of. Reverse Polish expressions are called postfix expressions, and the expression comes after the operand.
Reverse Polish expression:
a+b ---> a,b,+
a+(b-c) ---> a, b,c,-,+
a+(b-c)*d ---> a,b,c,-,d,*,+
a+d*(b-c)--->a ,d,b,c,-,*,+
a=1+3 ---> a=1,3 +
http=(smtp+http+telnet)/ What is written as 1024?
http=smtp,http,+,telnet,+,1024,/
Use Java to implement reverse Polish expression
/** * 计算算数表达式的值 * For example: * ["2", "1", "+", "3", "*"] -> ((2 + 1) * 3) -> 9 * ["4", "13", "5", "/", "+"] -> (4 + (13 / 5)) -> 6 * @author zl * 思路: * 这个问题可以通过使用堆栈来解决。 * (1)我们可以循环遍历给定数组中的每个元素。 * (2)当它是一个数字,把它推到堆栈。 * (3) 当它是一个操作符时,从堆栈中弹出两个数字,进行计算,并推回结果。 * */ public class EvaluateValueOfArithmeticExpression { private static void evoe(String[] strArr){ String str = "+-*/"; Stack<String> stack = new Stack<String>(); //2.0遍历数组中的每一个元素 for(String s : strArr){ if(!str.contains(s)){//如果是数字,放入栈中 stack.push(s); }else{ int a = Integer.valueOf(stack.pop()); int b = Integer.valueOf(stack.pop()); switch(s){ case "+" : stack.push(String.valueOf(a+b)); break; case "-" : stack.push(String.valueOf(b-a)); break ; case "*" : stack.push(String.valueOf(a*b)); break; case "/" : stack.push(String.valueOf(b/a)); break ; } } } System.out.println(stack.pop()); } public static void main(String[] args) { //1.0创建数组 String [] strArr = { "0", "2", "-", "3", "+" }; evoe(strArr); }
Summary
The above is the detailed content of Example of reverse Polish expression implementation in Java. For more information, please follow other related articles on the PHP Chinese website!