Writing a simple equation parser

前端 未结 10 1160
-上瘾入骨i
-上瘾入骨i 2020-12-01 03:56

What sorts of algorithms would be used to do this (as in, this is a string, and I want to find the answer):

((5 + (3 + (7 * 2))) - (8 * 9)) / 72
10条回答
  •  北海茫月
    2020-12-01 04:41

    The easiest way to solve this is to implement the Shunting Yard algorithm to convert the expression from infix notation to postfix notation.

    It's Easy-with-a-capital-E to evaluate a postfix expression.

    The Shunting Yard algorithm can be implemented in under 30 lines of code. You'll also need to tokenize the input (convert the character string into a sequence of operands, operators, and punctuators), but writing a simple state machine to do that is straightforward.

提交回复
热议问题