Basic Calculator II
On this page
Problem statement
Given a string with non-negative integers, the operators + − * / and spaces (no brackets), evaluate it with the usual precedence and return the result. Integer division truncates toward zero. The expression is always valid, and you may not use a built-in expression evaluator.
The problem tests whether you can handle operator precedence in one pass without building a parser. The trick is to treat the expression as a sum of terms and to finish each multiplication or division as soon as you see it. Original problem: LeetCode 227.
Example

Input: "3 + 2 * 2 - 8 / 3"
Output: 5
Input: " 3/2 "
Output: 1
Constraints (assumed)
- 1 ≤ length ≤ 300,000.
- Numbers fit in 32 bits, and so does every intermediate result.
What this question tests
- Handling precedence with a stack of terms instead of a full parser.
- Careful tokenizing: multi-digit numbers, spaces, the last number.
- Knowing your language's integer division rules for negative numbers.
Questions to ask first
- Can there be brackets or unary minus? (Here: no. With brackets, see Basic Calculator I/III.)
- How does division round? (Here: toward zero, so −8 / 3 is −2.)
- Can there be spaces anywhere? (Yes; skip them.)
- Can intermediate values overflow? (Here: no, but use 64-bit if unsure.)
Try it yourself first
You have the full problem. Sketch your answer, then sign up free to read the complete walkthrough.
- The complete design, flow by flow, with pictures
- Deep dives into the hard parts
- What mid, senior and staff candidates are expected to say
- Full company question lists
Free forever. No card needed.