The string s holds an arithmetic expression: non-negative whole numbers joined by the four operators +, -, * and /, with spaces sprinkled in. Work out its value and return it.
The usual rules of arithmetic apply:
* and / bind tighter than + and -.8/4*2 is (8/4)*2./ is whole-number division that drops the fractional part, rounding toward zero: 11/4 is 2.Evaluate it yourself: don't hand the string to a built-in that evaluates expressions, such as eval().
The multiplication comes first: 4*5 = 20. Then left to right, 6 + 20 = 26 and 26 - 8 = 18.
14/4 is 3.5, and the .5 is dropped. The spaces around it change nothing.
/ and * are applied left to right: 9/2 = 4, then 4*3 = 12. Last, 1 - 12 = -11.
Constraints
1 <= s.length <= 3 * 10⁵s is made of digits, +, -, *, / and spaces. Spaces may appear anywhere except inside a number, including at the start and end of s.s is a valid expression: every operator stands between two numbers. There are no brackets and no sign in front of a number: -3 and +3 never appear on their own.s is between 0 and 2³¹ - 1./ is non-zero.* and / only ever join neighbouring numbers into a single term, and + and - then add the terms up. Build the terms as you read, and add them together at the end.
* and / bind tighter than + and -, which sounds like you need to look ahead or build a tree. You don't. Look at what the expression really is: a sum of terms, separated by + and -, where each term is a run of numbers joined by * and /. In 6+4*5-8 the terms are 6, 4*5 and -8.
Time O(n)Space O(1)
The full walkthrough and code are part of Premium
18