LeetCode 227: Basic Calculator II

Claire Lee
3 min readDec 25, 2022

--

Given a string that contains digits and '+-*/' presenting a valid expression, implement a basic calculator to evaluate it. Use a variable tempResult to save the intermediate result. When we encounter '+', '-', '*' or '/'operators , evaluate the expression to the left of the previous operator. Add tempResult to final result if previous operator is '+' or '-' . Multiply or divide tempResult by the operand if previous operator is '*' or ‘/ respectively.

Basic calculator II summary card

String consists of digits, '+' , '-', '' and '/'

227. Basic Calculator II

Example:
Input: "10 + 2*3 - 6/3"
Output: 14

According the order of operations, we should perform multiplication and division first. Therefore, we aren’t able to evaluate the expression to the left immediately once we encounter '+', '-', '*' or '/'operators.

Instead, we use a variable tempResult to save the intermediate result and evaluate the expression to the left of the previous operator as we met a '+', '-', '*' or '/'operator.

  • If the previous operator is '+' or '-' , we add tempResult to final result.
  • If the previous operator is '*', we multiply tempResult by the operand.
  • If the previous operator is '/', we divide tempResult by the operand.
string consists +-*/

Graph Explanation

1
2
3
4

Code Implementation

  • Complexity
    Time: O(n) one pass
    Space: O(1)
    n: the length of the string expression

Golang

Python

You can access the source code here.

LeetCode Questions:

Related Story:

--

--

Claire Lee
Claire Lee

No responses yet