Basic Calculator
Try to solve the Basic Calculator problem.
We'll cover the following
Statement#
Given a string containing an arithmetic expression, implement a basic calculator that evaluates the expression string. The expression string can contain integer numeric values and should be able to handle the “+” and “-” operators, as well as “()” parentheses.
Constraints:
Let s be the expression string. We can assume the following constraints:
-
s.length sconsists of digits, “+”, “-”, “(”, and “)”.srepresents a valid expression.- “+” is not used as a unary operation ( and are invalid).
- “-” could be used as a unary operation ( and are valid).
- There will be no two consecutive operators in the input.
- Every number and running calculation will fit in a signed 32-bit integer.
Examples#
1 of 2
2 of 2
Understand the problem#
Let’s take a moment to make sure you've correctly understood the problem. The quiz below helps you check if you're solving the correct problem:
Basic Calculator
What is the output if the following string is given as input?
(13 + 50) + (56 - 29 - (7 + 2))
-81
81
91
90
Figure it out!#
We have a game for you to play. Rearrange the logical building blocks to develop a clearer understanding of how to solve this problem.
Note: We'll evaluate the expression in the following sequence:
1) Convert consecutive digits into a single operand.
2) Handle "+", "-" operators.
3) Handle the "(" bracket.
4) Handle the ")" bracket.
Try it yourself#
Implement your solution in the following coding playground:
Note: You can not use Python’s built-in
eval()function to solve this challenge.
Stacks: Introduction
Solution: Basic Calculator