medium +25 pts

Basic Calculator II

Evaluate a string expression with +, -, *, / without parentheses.

Implement a function `calculate(s: str) -> int` that evaluates a given string `s` representing a valid arithmetic expression containing only non-negative integers and the operators `+`, `-`, `*`, and `/`. The expression can contain spaces, but no parentheses. Division should be integer division truncating toward zero (e.g., `-7/2 = -3`). The expression is guaranteed to be valid (no division by zero). The function should return the integer result after applying standard operator precedence (`*` and `/` before `+` and `-`), with all operations performed left-to-right for equal precedence (e.g., `14/3*3 = 12` because `14/3=4`, then `4*3=12`). Note that integer division truncates toward zero in typical programming languages, so use truncation, not floor. Input length is between 1 and 300,000 characters.

Constraints

1 <= s.length <= 300,000 `s` consists of digits, spaces, and the characters `+`, `-`, `*`, and `/`. Every number is non-negative integer without leading zeros (except `0` itself). The expression is valid: operators appear between numbers, and division by zero never occurs. The result fits in a 32-bit signed integer. Do not use `eval()` or any similar function.

Example

```python
>>> calculate("3+2*2")
7
>>> calculate(" 14-3/2 ")
13
>>> calculate(" 3/2 ")
1
>>> calculate("42")
42
```
25 points ~30 min

Recent Submissions

No submissions yet — hit Run Tests to try!

Hints

Scan the string left to right. Keep track of the last number and the last operator, and use a stack to handle precedence.
When you see `*` or `/`, it should be applied immediately to the last number, updating the stack's top.
Use `int(current_num)` to parse multi-digit numbers and ignore spaces by skipping them.
Remember to handle the final number after the loop ends.
Python 3
All tests passed!
Test Results
Press Ctrl+Enter or click Run Tests to execute your code.