LeetCode 227: Basic Calculator II
Given a string that contains digits and
'+-*/'
presenting a valid expression, implement a basic calculator to evaluate it. Use a variabletempResult
to save the intermediate result. When we encounter'+', '-', '*' or '/'
operators , evaluate the expression to the left of the previous operator. AddtempResult
to final result if previous operator is'+' or '-'
. Multiply or dividetempResult
by the operand if previous operator is'*' or ‘/
respectively.
Table of Contents
· String consists of digits, '+' , '-', '∗' and '/'
∘ Graph Explanation
∘ Code Implementation
∘ Golang
∘ Python
String
consists of digits, '+' , '-', '
∗' and '/'
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 addtempResult
to final result. - If the previous operator is
'*'
, we multiplytempResult
by the operand. - If the previous operator is
'/'
, we dividetempResult
by the operand.
*
/Graph Explanation
Code Implementation
- Complexity
Time: O(n) one pass
Space: O(1)
n: the length of the string expression