Positive-Integer Expression Evaluation
Problem statement
Evaluate an arithmetic expression containing positive-integer literals, parentheses, and +, -, *, and /.
Every intermediate result must remain a positive integer. Immediately reject the expression if subtraction produces zero or a negative value, or if division has a nonzero remainder. A later operation cannot rescue an invalid intermediate result.
For this exercise, use ordinary arithmetic precedence: parentheses first, then multiplication and division, then addition and subtraction. Operators with equal precedence are left-associative. There are no unary operators, and spaces between tokens may be ignored. The expression is syntactically valid.
Return the final positive result as a decimal string, or the exact string "False" when an intermediate result is invalid. Implement the expression splitting or parsing within your solution; no external parsing helper is needed.
Function
evaluateExpression(expression: String) → StringExamples
Example 1
expression = "(3 + (3 * 5)) / 2"return = "9"Compute 3 * 5 = 15, then 3 + 15 = 18, then 18 / 2 = 9. Every intermediate value is a positive integer.
Example 2
expression = "((3 - 5) + 12) / 2"return = "False"The first subtraction produces -2. Reject immediately, even though completing ordinary arithmetic would yield a positive integer.
Example 3
expression = "8 / 12"return = "False"The division does not produce an integer.
Constraints
- For this exercise, assume
1 <= expression.length <= 500. - Every literal is an integer in
[1,10^6]with no leading zero. - Input uses decimal digits, the four operators, parentheses and ASCII spaces.
- Every positive intermediate arithmetic result is at most
10^9; use signed 64-bit arithmetic for multiplication before validation.