Stack Formula Interpreter
Problem statement
You are building a small stack interpreter that evaluates formulas. A formula is a string of tokens separated by single spaces. The interpreter starts with an empty stack and reads the tokens from left to right:
- An integer literal, such as
12or-3, pushes its value onto the stack. - An operator
+,-,*or/pops the top value as the right operand, then pops the next value as the left operand, and pushesleft op right. - Division truncates toward zero, so
-7 / 2is-3.
A token is an operator only when it is exactly one of those four characters. A token such as -3 is a negative literal, not a minus sign. After the last token, exactly one value is left on the stack, and that value is the formula's value.
Given an array formulas, evaluate each formula on its own, starting from an empty stack every time. Return an array with the value of each formula, in the same order.
Function
evaluateFormulas(formulas: String[]) → int[]Examples
Example 1
formulas = ["3 4 +","10 2 8 * -","7"]return = [7,-6,7]Each formula starts with an empty stack.
"3 4 +": push3and4;+pops them and pushes3 + 4 = 7."10 2 8 * -": push10,2and8;*pops8and2and pushes2 * 8 = 16;-pops16(right) and10(left) and pushes10 - 16 = -6."7": a single literal; its value is7.
Example 2
formulas = ["-7 2 /","7 -2 /","5 -3 -"]return = [-3,-3,8]"-7 2 /" computes -7 / 2 = -3.5, which truncates toward zero to -3 (not -4). "7 -2 /" also gives -3.
In "5 -3 -", the token -3 is a negative literal and the last - is the operator, so the value is 5 - (-3) = 8.
Example 3
formulas = ["6 2 3 + * 8 4 / -"]return = [28]6,2,3are pushed; the stack is[6, 2, 3].+replaces2, 3with5:[6, 5].*replaces6, 5with30:[30].8and4are pushed:[30, 8, 4];/replaces8, 4with2:[30, 2].-replaces30, 2with30 - 2 = 28, the only value left.
Constraints
1 <= formulas.length <= 1001 <= formulas[i].length <= 1000- Each
formulas[i]consists of tokens separated by single spaces, with no leading or trailing space. - Each token is
+,-,*,/, or an integer literal: an optional-followed by decimal digits with no leading zeros. Zero is written0, never-0. - Every formula is well-formed: each operator finds at least two values on the stack, and exactly one value is left after the last token.
- No formula divides by zero.
- Every literal and every intermediate value is in the range
[-2^31, 2^31 - 1].