Skip to content
DeepForgeby svx
All problems
MediumAlgorithmsal-284

Basic Calculator

Problem

Evaluate a string arithmetic expression containing non-negative integers, the operators +, -, * and /, and spaces, without parentheses.

Track the previous operator and a stack: numbers are pushed, negated or combined with the top of the stack for multiplication and division. Division truncates toward zero.

Hint

Appending a sentinel plus sign forces the final number to be processed.

Test cases

case 1
in: ["3+2*2"]
expected: 7
case 2
in: [" 3/2 "]
expected: 1
case 3
in: [" 3+5 / 2 "]
expected: 5
case 4
in: ["14-3/2"]
expected: 13
case 5
in: ["1+1"]
expected: 2
Starter codePython
def basic_calculator(s):
    # Your code here
    pass

5 test cases · run your code against them in the editor