Stacks and Queues Matching and cancelling
203. Basic Calculator II
You are given a string s that holds an arithmetic expression. Return its value.
The expression is made of non-negative integers and the four operators +, -, * and /. Any number of
spaces can sit between them, and at the start and the end. There are no brackets and no negative numbers.
Calculate it with the usual rules: * and / are applied before + and -, and operators at the same
level are applied from left to right. So 2 + 3 * 4 is 14, and 8 / 2 * 3 is 12. Division between
integers drops the remainder, which means it truncates toward zero: 7 / 2 is 3.
Do not use a built-in function that evaluates a string as an expression, such as eval.
Example 1
Input: s = "4 + 18 / 3 * 2 - 5"
11Explanation: * and / come first, from left to right: 18 / 3 = 6, then 6 × 2 = 12. That leaves 4 + 12 − 5,
which is 11.
Example 2
Input: s = " 14-3/2 "
13Explanation: The spaces at the start and the end change nothing. 3 / 2 is 1.5, and dropping the remainder gives 1. Then 14 − 1 = 13.
Example 3
Input: s = "2147483647 * 2 + 1"
4294967295Check your understanding
Work out the answer for this input before you write any code.
Constraints
1 ≤ s.length ≤ 3 × 105sholds only digits, spaces and the characters'+','-','*'and'/'sis a valid expression: ignoring spaces, it starts and ends with a number, and numbers and operators take turns. No space falls inside a number.- Every number is between
0and231 − 1, written in decimal with no leading zeros - No division has a divisor of
0 - Calculated with the usual rules, the result of every operation is between
-1015and1015
Clarifying questions
What you would ask an interviewer before writing any code.