Basic Calculator II
Medium · stack
A tiny calculator receives its sum as text. Given a string s holding an arithmetic expression, return its value.
The expression is made of non-negative whole numbers and the four operators +, -, * and /, with any number of spaces between them. There are no brackets.
*and/are done before+and-.- Operators of the same kind are done from left to right, so
8 - 3 - 2is3. /is whole-number division that rounds toward zero, so7 / 2is3and0 - 7 / 2is-3.
The expression is always valid, there is never a division by zero, and every value that appears while you work it out fits in a signed 32-bit integer.
Examples
Example 1
Input: s = "3+2*2"
Output: 7
The multiplication goes first: 2 * 2 = 4, then 3 + 4 = 7.
Example 2
Input: s = " 3/2 "
Output: 1
3 divided by 2 is 1.5, which rounds toward zero to 1.
Example 3
Input: s = " 3+5 / 2 "
Output: 5
5 / 2 is 2, and 3 + 2 is 5.
Example 4
Input: s = "0-7/2"
Output: -3
7 / 2 is 3, and 0 - 3 is -3.
Constraints
- 1 <= len(s) <= 3 * 10^5
- s contains digits, spaces and the characters '+', '-', '*' and '/'.
- s is a valid expression: numbers and operators alternate, it starts and ends with a number, and no number is split by a space.
- Every number is between 0 and 2^31 - 1, and every value that appears during evaluation fits in a signed 32-bit integer.
- There is no division by zero.