#K67722. Evaluate Mathematical Expression
Evaluate Mathematical Expression
Evaluate Mathematical Expression
You are given a string s that represents a mathematical expression. The expression contains positive integers and may include the operators for addition (+
), multiplication (*
), division (/
), and parentheses ( )
. The expression should be evaluated according to the usual operator precedence rules where multiplication and division have higher precedence than addition. Parentheses can override the normal precedence.
In mathematical terms, you are to compute the value of an expression that can be formally defined by the grammar:
$$\text{Expression} \to \text{Term} \;\{+\;\text{Term}\}\
\text{Term} \to \text{Factor} \;\{(* \text{ or } /)\;\text{Factor}\}\
\text{Factor} \to \text{Number} \;|\; (\text{Expression})
$$
If the expression is invalid (for example, if it contains illegal characters or malformed parentheses), print an error message in the exact format: Invalid expression: <expression>
(without quotes), where <expression>
is the original input string.
Note that if the computed result is an integer, print it as an integer; otherwise, print the floating-point number as produced by the evaluation.
inputFormat
The input is read from standard input (stdin). It consists of a single line containing the expression string s. The expression may contain spaces.
outputFormat
Output the result of the evaluation to standard output (stdout). If the expression is valid, print its numerical result (printing an integer if the result is a whole number and a float if not). Otherwise, print the error message exactly in the format Invalid expression: <expression>
.
3+2*2
7
</p>