Add missing left parentheses into equation [closed]

北城以北 提交于 2019-12-06 11:03:42

I think that the goal is assuming that you only parenthesize expressions, not lone numbers.

So you'll want to grab each token and toss them on a stack

2
+
1

grab the next token, which is ) now take the top three of the stack and sandwich it between those parens ( 1 + 2 ), put it back on the stack as one expression.

next push the stack looks like this

4
-
3
*
(1 + 2)

pull out the top three and put it back on the stack parenthesized (3-4) * (1+2)

and again

6
-
5
*
(3-4)
*
(1+2)

we hit another paren and grab the top 3 from the stack again, parenthesize and push back

(5-6)
*
(3-4)
*
(1+2)

We grab another paren, grab the top 3 from the stack again, parenthesize and push back

((3-4)*(5-6))
*
(1+2)

and again...

((1 + 2) * ((3 - 4) * (5 - 6)))

no more input, so this is our answer

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!