Given an expression 2 * (3-1), the computer immediately knows that the answer is 4, but does not have such capabilities. It only knows direct calculation, but does not know the priority. In this way, we need to use code to tell its operator priority.
- From left to right
- Multiplication, division, and addition and subtraction
- Inside and out of brackets
First, we will study simple arithmetic expressions, with only the +-*/() operator.
Operator priority table, where # Is the end identifier.
The specific implementation is now entangled.
/// <Summary> /// returns the priority of the two operators /// </summary> /// <param name = "first"> </param> // <param name = "last"> </param> // <returns> ">, <, = "</returns> private char Precede (char first, char last) {string operate =" +-*/() # "; char [,] level = new char [7, 7] {'>', '>', '<', '>', '> '}, {'>', '>', '<', '>', '>'}, {'>', '> ', '>', '>', '<', '>', '>'}, {'>', '>', '<', '<', '<', '>', '>'}, {'<', '<', '= ', ''}, {'>', ','> ',' = '}, {' <', '<', ',' = '}; int rows = operate. indexOf (first); int cols = operate. indexOf (last); return level [rows, cols];}
Mainly to display the table content, return >,<,=.
Arithmetic expression calculation algorithm. The parameter is assumed to be a standard infix expression. Otherwise, an exception occurs.
/// <Summary> /// operator Priority Algorithm /// </summary> /// <param name = "infixExpression"> infixExpression </param> /// <returns> </returns> public int ComputeExpression (string infixExpression) {Stack <int> stackOperand = new Stack <int> (); // operand Stack <char> stackOperator = new Stack <char> (); // operator Stack stackOperator. push ('#'); // as the end of the empty stack, infixExpression = infixExpression + "#"; // The End Of The infix expression, int temp = 0; int result = 0; int count = 0; c Har cur = infixExpression [count]; while (cur! = '#' | StackOperator. Peek ()! = '#') // After scanning the arithmetic expression, and the operator stack is empty {if (cur = '') continue; if (IsOperand (cur )) // The operands are directly written into the stack {stackOperand. push (Int32.Parse (cur. toString (); cur = infixExpression [++ count]; // scan arithmetic expression next bit} else {switch (Precede (stackOperator. peek (), cur) // compare the top element of the operator stack and the priority of the current operator scanned {// if the current operator has a higher priority, it is directly imported into the stack, placed at the top of the stack (priority must be calculated first) case '<': stackOperator. push (cur); cur = infixExpression [++ count]; break; // equals to indicate that the top element of the stack is left parenthesis, and the current character is right brace case '=': stackOperator. pop (); // Pop up the left bracket cur = infixExpression [++ count]; break; // the priority of the current operator is small, the top operator of the stack is displayed, and two operands are displayed from the stack: case '>': temp = stackOperand. pop (); result = stackOperand. pop (); // pay attention to the calculation order. The calculation result is added to the operand stack. Then, compare the new stack top operator with the current operator's priority stackOperand. push (Operate (result, temp, stackOperator. pop (); break ;}} return stackOperand. peek ();}
The above method directly accepts the infix expression to calculate the result.
Calculator (more operators, not necessarily binary operators), I believe it is not difficult to expand
Filtering Method (generally, the filtering algorithms in the Forum are the contains method in the framework). The contains method can only be (s1and s2 and s3 ...), The operator priority algorithm can be (s1and s2) or (s3) and s4 and a series of other expressions
Another operator priority algorithm is to first convert the standard infix expression into a suffix expression (inverse polish expression), and then use a stack to store the computing results to implement inverse Polish calculation.
Not detailed
Public string InfixToPostfix (string infixExpression) {Stack <char> stackOperand = new Stack <char> (); // operand Stack <char> stackOperator = new Stack <char> (); // operator for (int I = 0; I <infixExpression. length; I ++) {if (infixExpression [I] = '') continue; char placement = infixExpression [I]; switch (break) {case '+ ': case '-': while (stackOperator. count> 0) {char ch = stackOperator. peek (); if (GetOperatorP Riority ('-') <= GetOperatorPriority (ch) {stackOperator. pop (); stackOperand. push (ch) ;}else {break ;}} stackOperator. push (break); break; case '*': case '/': while (stackOperator. count> 0) {char ch = stackOperator. peek (); if (GetOperatorPriority ('*') <= GetOperatorPriority (ch) {stackOperator. pop (); stackOperand. push (ch) ;}else {break ;}} stackOperator. push (partial); break; case '(': stackOpe Rator. Push (iterator); break; case ')': while (stackOperator. Count> 0 & stackOperator. Peek ()! = '(') {Char ch = stackOperator. pop (); stackOperand. push (ch);} stackOperator. pop (); break; default: stackOperand. push (iterator); break;} while (stackOperator. count> 0) {stackOperand. push (stackOperator. pop ();} StringBuilder sb = new StringBuilder (); for (int I = stackOperand. count; I> 0; I --) {sb. insert (0, stackOperand. pop ();} return sb. toString ();}
public int ComputeArithmeticExpression(string postfixExpression) { Stack<int> stackResult = new Stack<int>(); int result = 0; int temp = 0; // for (int i = 0; i < postfixExpression.Length; i++) { char expr = postfixExpression[i]; switch (expr) { case '+': result = stackResult.Pop() + stackResult.Pop(); stackResult.Push(result); break; case '-': temp = stackResult.Pop(); result = stackResult.Pop() - temp; stackResult.Push(result); break; case '*': result = stackResult.Pop() * stackResult.Pop(); stackResult.Push(result); break; case '/': temp = stackResult.Pop(); result = stackResult.Pop() / temp; break; default: stackResult.Push(Int32.Parse(expr.ToString())); break; } } result = stackResult.Pop(); return result;}