cswork / libraryOpen practice workspace

Coding questions · Aurora

Evaluate an Arithmetic Expression

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.

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

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

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.

Evaluate an Arithmetic Expression

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.

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.

Approach

Maintain the sum of completed additive terms plus the current multiplication/division term. Applying each pending operator when the next operator arrives naturally enforces precedence and left associativity.

  • Time complexity: O(n)
  • Space complexity: O(1)