Community

Start a Thread


Notifications
Subscribe You’re not receiving notifications from this thread.

Build a Calculator (Main Thread)

Here is the interview question prompt, presented for reference.

Let's build a very basic calculator by programming it! You've probably seen one that look similar to this:

But we won't be building a physical calculator (HardwareDaily will need to wait!)-- instead, we'll be writing a simple program that can serve as one. Can you write a function that will evaluate a simple expression string without using your language's eval method?

const expr = "2 + 2";
calculator(expr)
// 4
expr = "2 + 2"
calculator(expr)
# 4

It should also be able to handle positive and negative symbols +,-, parentheses (), and spaces.

let expr = "3 - 1 + 2";
calculator(expr)
// 4

expr = "(2+(4+2)-1)-(5+8)"
calculator(expr)
// -6
expr = "3 - 1 + 2"
calculator(expr)
# 4

expr = "(2+(4+2)-1)-(5+8)"
calculator(expr)
# -6

Assume for now that you don't need to handle multiplication or division cases.

Constraints

  • Length of the given string <= 100000
  • The numbers present in the string will be a single digit number
  • Expected time complexity : O(n)
  • Expected space complexity : O(n)

You can see the full challenge with visuals at this link.

Challenges • Asked over 6 years ago by Jake from AlgoDaily

Jake from AlgoDaily Commented on Nov 30, 2017:

This is the main discussion thread generated for Build a Calculator.