Basic Calculator

Try to solve the Basic Calculator problem.

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×104\leq 3 \times 10^{4}
  • 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#

Created with Fabric.js 3.6.6 Sample example 1 (8 + 100) + (13 - 8 - (2 + 1)) 110

1 of 2

Created with Fabric.js 3.6.6 Sample example 2 (46 - 12) + (13 - 8) 39

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

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

Question 1 of 40 attempted

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.

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

Initialize a stack to manage nested expressions and three variables for the current number, sign value, and result.

Iterate through the input string to process the equation. Determine if the character is a digit, parenthesis, or operator.

When encountering a digit, update the number variable by appending the digit to it.

For operators (+ and -), compute the left expression using the current sign and update the result.

If an opening parenthesis is found, push the current result and sign onto the stack for nested expressions. For a closing parenthesis, compute the expression within it and update the result.

Once the whole expression is traversed, return the final result, which represents the evaluated arithmetic expression.


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.

Python
usercode > main.py
Input #1
Basic Calculator

Solution: Implement Queue Using Stacks

Solution: Basic Calculator