One Pager Cheat Sheet

  • Let's program a very basic calculator, handling positive, negative symbols, parentheses, and spaces, without using eval function!
  • In most languages, you can evaluate code strings quickly and easily using eval.
  • We can break down the problem into parsing and evaluating symbols such as integers, signs/operations, parenthesis and spaces, and iterate through an expression string to transform it into a form understandable by the machine, with some caveats in the processing order.
  • Adding a negative number to our running result is the key to solving the problem of subtraction.
  • We can keep track of our sign while converting the signs of numbers by using 1 or -1 to represent the + or - operations respectively.
  • Leveraging two stacks to keep track of the result and operations within the parentheses is the key to solving this challenging problem.
  • We skip that iteration if the current character is a space.
  • We can iterate through the input of length n in O(n) time and space complexity.
  • We can extend our previous solution to handle Multiplication and Division by using a stack to store multipliers and dividers and multiplying or dividing the result of each for loop iteration by this stack as it pops values off.
  • Byrecreatingthe parentheses expression on a stack, we can still use the left-to-right approach to parse"4*(3+2)", instead of being "drawn to the parentheses".

This is our final solution.

To visualize the solution and step through the below code, click Visualize the Solution on the right-side menu or the VISUALIZE button in Interactive Mode.

JAVASCRIPT

That's all we've got! Let's move on to the next tutorial.

If you had any problems with this tutorial, check out the main forum thread here.