Search⌘ K
AI Features

Basic Calculator

Explore how to implement a basic calculator that evaluates arithmetic expressions containing integers, plus and minus operators, and parentheses. Learn to use stacks effectively to parse and compute the result, handle unary minus, and manage operator precedence. This lesson helps you understand the stack-based approach to solving expression evaluation problems in coding interviews.

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:

  • 11 \leq s.length 3×103\leq 3 \times 10^{3}
  • s consists of digits, “+”, “-”, “(”, and “)”.
  • s represents a valid expression.
  • “+” is not used as a unary operation ( +1+1 and +(2+3)+(2 + 3) are invalid).
  • “-” could be used as a unary operation (1-1 and (2+3)-(2 + 3) 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

1.

What is the output if the following string is given as input?

(13 + 50) + (56 - 29 - (7 + 2))

A.

-81

B.

81

C.

91

D.

90


1 / 4

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.

Sequence - Vertical
Drag and drop the cards to rearrange them in the correct sequence.

1
2
3
4
5
6

Try it yourself

Implement your solution in the following coding playground:

C++
usercode > main.cpp
int Calculator(string expression) {
// Replace this placeholder return statement with your code
return 0;
}
Basic Calculator