educative.io

Basic Calculator - I dont understand the solution at all, it relies on memorizing the approach

To instructors,

I really don’t understand the solution at all. it is not at all intuitive and reading such a complex solution is not helping at all.

I don’t believe this can be solved if one does not memorize/rote/mug up the approach because this is not intuitive approach. Can you please provide an ALTERNATIVE solution that is more intuitive where you DONT have to remember the approach?

I am not looking for an explanation on current method you have shown. I am looking for an ALTERNATIVE way to solve this than presented here. Is there only 1 way to solve this?


Course: https://www.educative.io/collection/10370001/5500262945128448
Lesson: https://www.educative.io/collection/page/10370001/5500262945128448/5082672275914752


Course: https://www.educative.io/collection/10370001/5500262945128448
Lesson: https://www.educative.io/collection/page/10370001/5500262945128448/5082672275914752

1 Like

awaiting a response


Course: https://www.educative.io/collection/10370001/5500262945128448
Lesson: https://www.educative.io/collection/page/10370001/5500262945128448/5590097835851776

1 Like

Hi @adityahpatel,

Apologies to keep you waiting. The basic calculator approach is solved with stacks because we have a string that we need to check character by character, similar to the balanced parentheses approach. We can intuitively solve this calculator problem as well. However, there is an alternative approach to solving this problem using recursion. This method breaks down the expression by recursively evaluating sub-expressions enclosed in parentheses. Here’s how you can do it:

  1. Scan the expression from left to right.
  2. When a number is encountered, convert it into an integer and add it to the result.
  3. When an operator is encountered, store it to apply to the next number.
  4. When an open parenthesis is encountered, recursively evaluate the expression inside the parentheses. Once the closing parenthesis is found, treat the evaluated result as a part of the current expression.
  5. When a closing parenthesis is encountered, return the result up to that point (along with the position of the closing parenthesis) to the previous level of recursion.

This method effectively handles nested expressions by breaking them down into simpler sub-expressions, which can be evaluated separately.

Let me know if you’re interested in going into the implementation part of this approach. I will help you out with that! Feel free to share further suggestions and feedback. We’d be happy to help!

Thanks!