Evaluation of Postfix Expressions

       In practical applications, since infix expressions are computationally complex and occupy a lot of space, suffix expressions can theoretically calculate expressions of arbitrary complexity, and use the characteristics of stacks to only calculate expressions each time. It is only necessary to operate on the top element of the stack, so the calculation efficiency will be greatly improved after converting the infix expression to the postfix expression.

       The calculation rule of the suffix expression is: when an operand (number) is encountered, it is pushed onto the stack, and when an operator is encountered, the two elements at the top of the stack are taken out, calculated according to the current operator, and the calculation result is pressed again. Push to the top of the stack. If the expression is a regular expression, after the entire expression is scanned, there will be only one number on the top of the stack, which is the result of the calculation.

       The specific code is as follows:

import java.util.Stack;

public class LastExpression {
  private static Stack<Float> stack = new Stack<>();
  public static Float compute(String str) {
    transfer(str);
    return stack.pop();
  }

  private static void transfer(String str) {
    for (int i = 0; i < str.length(); i++) {
      switch (str.charAt(i)) {
        case ' ':
          continue;
        case '+':
          plus();
          break;
        case '-':
          sub();
          break;
        case '*':
          I have();
          break;
        case '/':
          div();
          break;
        default:
          i = num(str, i);
      }
    }
  }

  private static int num(String str, int index) {
    StringBuilder numStr = new StringBuilder("");
    Character ch = null;
    while (index < str.length() && ((ch = str.charAt(index)) <= '9' && ch >= '0')) {
      numStr.append(ch);
      index++;
    }
    stack.push(Float.parseFloat(numStr.toString()));
    return index - 1;
  }

  private static void plus() {
    Float a = stack.pop();
    Float b = stack.pop();
    stack.push(a + b);
  }

  private static void sub() {
    Float a = stack.pop();
    Float b = stack.pop();
    stack.push(a - b);
  }

  private static void mul() {
    Float a = stack.pop();
    Float b = stack.pop();
    stack.push(a * b);
  }

  private static void div() {
    Float a = stack.pop();
    Float b = stack.pop();
    stack.push(a / b);
  }
}

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=326786866&siteId=291194637