Implement a basic calculator for expressions without parentheses. The source describes it only as "the basic version, without parentheses". This version uses the four operators +, -, * and / on non-negative integers.
Given the expression as a string, evaluate it and return the integer result.
Function Signature
def evaluate(expression: str) -> int:
Rules
-
The expression contains non-negative integer literals, the binary operators
+
,
-
,
*
and
/
, and spaces, which may appear anywhere and are ignored.
-
*
and
/
bind tighter than
+
and
-
. Operators of equal precedence are evaluated left to right.
-
/
is integer division that discards the fractional part (rounding toward zero).
-
There are no parentheses and no unary operators, the expression is always valid, and division by zero never occurs.
-
Do not use
eval
or a similar built-in expression evaluator.
Constraints
-
1 <= len(expression) <= 3 * 10^5
-
expression
consists of digits,
'+'
,
'-'
,
'*'
,
'/'
and
' '
, and contains at least one integer.
-
Every integer literal is between
0
and
2^31 - 1
.
-
Every intermediate result and the final result are between
-2^31
and
2^31 - 1
.
Examples
Example 1
Input: expression = "14 - 3 * 4 / 5"
Output: 12
3 * 4 = 12, then 12 / 5 = 2, and 14 - 2 = 12.
Example 2
Input: expression = " 8 / 3 * 3 + 1"
Output: 7
8 / 3 = 2, then 2 * 3 = 6, and 6 + 1 = 7.
Example 3
Input: expression = "2 - 3 - 4"
Output: -5
Subtraction is evaluated left to right: (2 - 3) - 4.