Skip to main content
Back to problems
Leetcode
Medium
Arrays
Strings
Stacks
Math
Google
Microsoft
Basic Calculator II

Evaluate a basic arithmetic expression containing non-negative integers, the operators +, -, *, and /, and optional spaces.

Acceptance 0%
Problem Statement

Problem

Given a string expression representing a basic arithmetic formula, compute its value.

The expression contains:

  • non-negative integers
  • the operators +, -, *, /
  • optional spaces

You must evaluate the expression using standard operator precedence:

  • * and / are performed before + and -
  • all division should truncate toward zero

The input is guaranteed to be a valid expression with no parentheses.

Notes

  • You may not use a built-in expression evaluator.
  • The result fits in a 32-bit signed integer.

Input Format

  • A single string s representing the arithmetic expression.
  • The string may contain spaces.
  • Integers are non-negative and operators are from the set {+, -, *, /}.

Output Format

  • Return an integer equal to the evaluated result of the expression.

Constraints

  • 1 <= s.length <= $10^{5}$
  • s contains digits, spaces, and the operators +, -, *, /
  • s is a valid expression
  • No parentheses are present
  • Division truncates toward zero
Examples
Sample cases returned by the problem API.

Example 1

Input

s = "3+2*2"

Output

7

Explanation

Multiply before adding: 2*2 = 4, then 3+4 = 7.

Example 2

Input

s = " 3/2 "

Output

1

Explanation

Division truncates toward zero, so 3/2 becomes 1.

Show 1 more example

Example 3

Input

s = " 3+5 / 2 "

Output

5

Explanation

First compute 5/2 = 2, then 3+2 = 5.

Premium problem context

Unlock deeper context for this problem

Premium adds guided hints, editorial links, similar variants, discussion resources, and concept maps so you can understand why a problem matters, not just solve it once.

Guided hints
Editorial and discussion links
Concept map and variants
Sign in to unlock
Track your progress
Sign in to bookmark this problem, save notes, and manage its revision plan.