Evaluate an arithmetic expression with +, -, *, / and parentheses
Implement a basic calculator that evaluates an arithmetic expression given as a string and returns its integer value.
The expression contains only non-negative integers, the operators +, -, * and /, and the parentheses ( and ). Multiplication and division are evaluated before addition and subtraction, operators of equal precedence are applied from left to right, and a parenthesized group is evaluated before its value is used. Integer division truncates toward zero.
You may assume the expression is always valid.
Function Signature
def calculate(expression: str) -> int:
Rules
-
Every operator is binary, with an operand on each side. An operand is a number or a parenthesized group. Unary signs, such as a leading
-
, do not appear.
-
A group can evaluate to a negative number, for example
(2-9)
. Division still truncates toward zero, so
-7
divided by
2
is
-3
.
-
No division by zero occurs.
Constraints
-
1 <= len(expression) <= 10^4
-
expression
consists only of digits,
+
,
-
,
*
,
/
,
(
and
)
.
-
expression
is a valid expression.
-
Every intermediate result is in the range
[-2^31, 2^31 - 1]
.
Examples
Input: expression = "6-4/2"
Output: 4
Division comes first: 4/2 = 2, then 6 - 2 = 4.
Input: expression = "2*(5+5*2)/3+(6/2+8)"
Output: 21
The first group is 5 + 10 = 15, so 2 * 15 / 3 = 10. The second group is 3 + 8 = 11, and 10 + 11 = 21.
Input: expression = "(2-9)/2+1"
Output: -2
The group is -7, and -7 / 2 = -3.5 truncates toward zero to -3 (floor division would give -4). Then -3 + 1 = -2.