Today, there is an interview in the afternoon. During the second interview, there was an algorithm question. I don’t know anything about algorithms. Please ask someone to help me.
The topic is to implement a function for calculating addition, subtraction, multiplication and division of parentheses. The input string is similar to (1 2)/4 5 (3 5)*3. Similar legal operations
Can you explain the general idea a little bit? The interviewer said earnestly that this was an algorithm question. I don’t think it should be an implementation of eval(), right?
Use the dispatching field algorithm to change the infix expression into a suffix expression (reverse Polish expression)
eval is a method, but it is relatively unstandardized and should not be used in most cases.
The four expressions of regular addition binary tree operation for this question
Use the stack to implement expression evaluation. On Baidu, there are some
You can use reverse Polish on data structure
The most common method is syntax analysis, building an expression tree, and then solving it.
You can write it yourself, or you can use a very professional and versatile library called Antlr.
Of course, during the interview, you should be asked to analyze the grammar and build the grammar tree yourself. When it comes to actually doing it, Antlr is better.
Algorithms and examples of parsing four arithmetic expressions in JavaScript,
Please take a look at it
Algorithms and examples of parsing four arithmetic expressions in JavaScript
I don’t recommend using the abandoned method of eval. 1. It is recommended to use regular expressions 2. How to use stacks in data structures
Recommend a book: Learning JavaScript data structures and algorithms
I just happened to be studying things like stacks, queues, and binary trees recently
This...if you input a string.
You can use eval() directly
var a = '(1+2)/4+5+(3+5)*3';
eval(a);
The commonly used method of parsing the four arithmetic operations of strings is the reverse Polish method
Use a stack to implement it. Two years ago when I was doing data structure experiments, I had one. It also had a formula legality check. I’m going to look for where to put it.
Okay, I can’t find it. My general impression is that I want to make one. Use a two-dimensional array to determine the operator priority, and then use the stack to calculate it