Writing a simple equation parser

前端 未结 10 1179
-上瘾入骨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:35

    If the expressions are known to be fully-parenthesized (that is, all possible parentheses are there), then this can easily be done using recursive-descent parsing. Essentially, each expression is either of the form

     number
    

    or of the form

     (expression operator expression)
    

    These two cases can be distinguished by their first token, and so a simple recursive descent suffices. I've actually seen this exact problem given out as a way of testing recursive thinking in introductory programming classes.

    If you don't necessarily have this guarantee, then some form of precedence parsing might be a good idea. Many of the other answers to this question discuss various flavors of algorithms for doing this.

提交回复
热议问题