Basic Calculator II

Free with account Updated Nov 19, 2026 · 5 min read
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

    In 3 + 2 * 2 − 8 / 3 the multiplication and division are done first, giving 3 + 4 − 2 = 5.
    In 3 + 2 * 2 − 8 / 3 the multiplication and division are done first, giving 3 + 4 − 2 = 5.
    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

    1. Can there be brackets or unary minus? (Here: no. With brackets, see Basic Calculator I/III.)
    2. How does division round? (Here: toward zero, so −8 / 3 is −2.)
    3. Can there be spaces anywhere? (Yes; skip them.)
    4. Can intermediate values overflow? (Here: no, but use 64-bit if unsure.)