Evaluate a Flat Expression or Report Invalid Input
Problem statement
Evaluate a flat arithmetic expression with nonnegative decimal integer operands and binary operators +, -, *, and /. Multiplication and division take precedence over addition and subtraction; operators at the same precedence are evaluated left to right. There are no parentheses or unary signs.
ASCII spaces may appear before, after, or between complete tokens, but not inside a number. Leading zeros are allowed. Divide integers by truncating toward zero. Return the decimal result as a string.
Return the exact string ERROR if the expression is empty or malformed, contains an unsupported character, has an operand larger than 10^6, or divides by zero. Examples of malformed syntax include adjacent operators, a missing operand, an unexpected parenthesis, and two numbers with no operator between them.
Function
evaluateFlatExpression(expression: String) → StringExamples
Example 1
expression = "10/2+1*3+5"return = "13"Evaluate division and multiplication first: 5 + 3 + 5 = 13.
Example 2
expression = "20-7/2*3"return = "11"7/2 truncates to 3, then 3*3 = 9, so the result is 11.
Example 3
expression = "1+*2"return = "ERROR"The addition operator lacks a number on its right, so the syntax is invalid.
Constraints
0 <= expression.length <= 100.- Valid operands are decimal integers from
0through10^6. - For valid arithmetic, every intermediate value and the final result fit a signed 64-bit integer.
- Only ASCII spaces are allowed as whitespace.