There was an interview question a few days ago: Calculate the string "1 + (5 - 2) * 3", the result is 10, and eval() cannot be used. Today, I will introduce the method of pushing the stack to solve this problem. In fact, the principle of our calculator is the same.
2 Summary algorithm
Through the analysis in 1, we can roughly sort out the following algorithm:
From the above analysis, we abstract several functions:
(1) A function that calculates the result of 'an expression composed of two numbers and operators' when popping the stack.
(2) A function that determines whether an element is a number or an operator.
(3) Process the equation into a function in the form of a list. For example: '-1-2*((-2+3)+(-2/2))' should be processed as: ['-1', '-', '2', '*', '(', '(', '-2', '+', '3', ')', '+', '(', '-2', '/', '2', ')', ')'] .
(4) Decision function, which decides whether to push into the stack, pop the stack for operation, or pop the stack to discard.
(5) The main function, which traverses the formula list and calculates the final result.
3 Two-number operation functions
Pass in two numbers, an operator, and return the corresponding result according to the operator. That is to calculate addition, subtraction, multiplication and division:
4 Determine whether it is an operator or a number
Here you may think of isdigit() to judge numbers, but this function cannot judge decimals and negative numbers. So, we write a function to determine whether it is an operator:
5 Formatting expressions as lists
What this step needs to deal with is to distinguish whether the horizontal bar '-' represents a negative number or a minus sign. See the following example for details, and the comments are very clear:
6 Decide whether to pop or push
This function is more difficult and more abstract. Compare two consecutive operators to determine whether to push or pop the stack:
7 Main function
The main function is responsible for traversing the characters in the formula list, and decides to enter the number stack or operator stack or pop the stack operation.
8 Ultimate Code and Testing
Let's take a look at the results of the Google calculation:
It means that we are right, let’s test some more formulas to see.
This article is over.
Pretending to be like the wind, always accompany me! So have you learned?