spiralgo / algorithms

We voluntarily solve algorithm problems on this repo.
24 stars 7 forks source link

772. Basic Calculator III #384

Closed ErdemT09 closed 3 years ago

ErdemT09 commented 3 years ago

Resolves: #229

Algorithm:

What we have to do here is parsing some given string into a numerical calculation. Here are few catches:

100-40/2/5 -> 40 gets subtracted from the previous sum 0 -> -40 Then previous sum divided by 2 yields -> -20 Same for 5 -> -4 At the end, it is added to the total sum, which was 100 -> 100+(-4)=96

calculate(e1*(e2+(e3))) What we should do is:

calculate(e1)*calculate(e2+(e3)) ->
calculate(e1)*(calculate(e2) + calculate(e3))

Which is pretty easy to implement using recursion, with closing parentheses terminating the recursion.

So, we need to keep track of the total sum, current operator and the current previous sum to implement these.