Quick Overview

Evaluate arithmetic expressions containing non-negative integers and the four basic operators without using eval. Preserve precedence and left associativity, implement division that truncates toward zero, and process expressions up to 300,000 characters efficiently.

Evaluate an Arithmetic Expression

Company: Aurora

Role: Software Engineer

Category: Coding & Algorithms

Difficulty: medium

Interview Round: Technical Screen

## Evaluate an Arithmetic Expression Implement a function that evaluates a valid arithmetic expression containing non-negative integers, the binary operators `+`, `-`, `*`, and `/`, and optional spaces. Use normal arithmetic precedence: multiplication and division are evaluated before addition and subtraction. Operators with the same precedence are evaluated from left to right. Integer division must truncate toward zero. ### Function Signature ```python def calculate(expression: str) -> int: ... ``` ### Input - `expression` is a nonempty string containing decimal digits, spaces, and the four supported operators. - The expression is syntactically valid and does not contain parentheses. - Every division has a nonzero divisor. ### Output Return the integer value of the expression. ### Constraints - `1 <= len(expression) <= 300_000` - Each numeric token represents a non-negative integer. - The final result and every intermediate value fit in a signed 32-bit integer. ### Examples ```text Input: "3+2*2" Output: 7 Input: " 14-3/2 " Output: 13 Input: "0-7/3" Output: -2 ``` ### Clarifications - Do not use `eval` or an equivalent expression-evaluation library. - The entire expression may be processed in one pass; constructing an abstract syntax tree is not required.

Quick Answer: Evaluate arithmetic expressions containing non-negative integers and the four basic operators without using eval. Preserve precedence and left associativity, implement division that truncates toward zero, and process expressions up to 300,000 characters efficiently.

Evaluate a valid expression of nonnegative integers, spaces, and +, -, *, / without parentheses. Multiplication and division precede addition and subtraction, equal-precedence operators are left-associative, and division truncates toward zero.

Constraints

  • The expression length is at most 300,000.
  • Every division has a nonzero divisor.
  • Inputs are syntactically valid and contain no parentheses.
  • Do not use eval or an equivalent evaluator.

Examples

Input: ('3+2*2',)

Expected Output: 7

Explanation: Multiplication precedes addition.

Input: (' 14-3/2 ',)

Expected Output: 13

Explanation: Spaces are ignored and positive division truncates.

Hints

  1. Accumulate a current number and the most recent multiplicative term.
  2. Commit the prior term when a lower-precedence boundary is reached.
  3. Implement truncation with absolute integer division and an explicit sign.

Loading coding console...