Skip to main content

Build a Calculator

Medium

We want to build a simple calculator that can solve arithmetic expressions like 2 + 2 or 4 * 5 - 10 * 2. Write a function calc(expr) that accepts a string as input and returns the answer as a number. It should follow the normal order of operations and support addition, subtraction, multiplication, and division. Don't worry about parentheses or improperly formatted strings.

Examples

calc("1 + 1") # => 2 calc("5 - 1 - 1") # => 3 calc("84 / 1 / 2") # => 42 calc("5/2 - 2*3") # => -3.5

Think about how you would solve the expression by hand and start with a simple example! You should solve sub-expressions like multiplication and division first, and then solve addition and subtraction.

Can you split the expression into sub-expressions and solve them individually?

Since you need the result of smaller expressions to calculate the final result, consider using a stack or recursion.

Does your solution solve the expression using the correct order of operations?

Does subtraction work as you would expect? What does "5 - 2 - 1" return?