The problem arises:
Reads a arithmetic expression in a string form, outputting the corresponding calculation result. If you read "6 * (5 + (2 + 3) * 8 + 3)", then the parsed output should be 288.
Ideas:
- The general calculation process is to first calculate the contents of the highest-priority parentheses, i.e. "(5 + (2 + 3) * 8 + 3)",
- The calculation results of "2 + 3" coexist with a, and then the "a*8" is calculated, and the coexistence is B
- Calculate "5+b+3" and Save as C
- Final calculation of "6*c", Calculation completed
We can write this sequence of operations as follows:
6 5 2 3 + 8 * + 3 + *
This notation is the inverse Polish (reverse Polish) expression, and its evaluation process happens to be the process described above. The inverse Polish expression is also called the suffix (postfix) expression. In the usual expression, the operator is always placed between the two operands associated with it, so this notation is also known as infix notation. In 1929, Polish logic House J.lukasiewicz proposed another way of expressing expressions. By this method, each operator is placed after its operand, so it is called a suffix representation.
Calculation of postfix expressions
The simplest way to calculate a suffix expression is to use a stack:
- When you read a number, push it into the stack.
- When an operator is read, two numbers are popped from the stack, and the operator is applied to the two numbers, and the results are then pushed back into the stack
Below is a demonstration of the process of "6 5 2 3 + 8 * + 3 + *"
- First read 6 5 2 34 numbers, nothing to say, directly into the stack (6 5 2 3)
- Read the operator "+", pop two Numbers "3", "2" from the stack, calculate 3+2 = 5, and press the calculation result into the stack; (6 5 5)
- Read 8, press-in stack (6 5 5 8)
- Reads "*", pops two numbers "8", "5" from the stack, calculates 8 * 5 = 40, and presses the calculation result into the stack; (6 5 40)
- Reads "+", pops two Numbers "40", "5" from the stack, calculates 40 + 5 = 45, and presses the calculation result into the stack; (6 45)
- Read 3, press-in stack (6 45 3)
- Reads "+", pops two Numbers "3", "45" from the stack, calculates 3 + 45 = 48, and presses the calculation result into the stack; (6 48)
- Read "*", pop out from the stack two numbers "48", "6", calculate 48 * 6 = 288, the calculation is complete!!!
The time to calculate a suffix expression is O (N), the algorithm is very simple to calculate, and does not need to know any computational priorities.
So the question now is how to convert a normal expression to a suffix expression???
And look at tell.
Java parsing string expression--calculation of inverse Polish expression