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.
100000
O(n)
O(n)
You can see the full challenge with visuals at this link.
Challenges • Asked almost 7 years ago by Jake from AlgoDaily
This is the main discussion thread generated for Build a Calculator.