Basic Calculator
Understand how to implement a basic calculator that evaluates arithmetic expressions containing integers, plus and minus operators, and parentheses. Explore the use of stack data structures to handle operator precedence and expression evaluation in C++. This lesson helps you develop a clear approach to parsing and computing valid mathematical expressions.
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
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:
int Calculator(string expression) {// Replace this placeholder return statement with your codereturn 0;}