408. Evaluate Expression with Integer Division

Fulltime8/23/2025
Meta

Problem Description

You are given a string expression consisting of integers, '+', '-', '*', '/' operators, and spaces. Evaluate the expression and return the result as an integer. Integer division should truncate toward zero. The expression will always be valid. No parentheses are allowed.

Examples

Example 1:
Input: 3+2*2
Output: 7
Explanation: 3 + (2 * 2) = 7
Example 2:
Input: 3/2
Output: 1
Explanation: 3 / 2 = 1
Example 3:
Input: 3+5 / 2
Output: 5
Explanation: 3 + (5 / 2) = 3 + 2 = 5
Example 4:
Input: 14-3/2
Output: 13
Explanation: 14 - (3 / 2) = 14 - 1 = 13
Example 5:
Input: 0-2147483647
Output: -2147483647
Explanation: 0 - 2147483647 = -2147483647

Constraints

  • ["1 <= s.length <= 3 * 10^5", "s consists of integers and operators ('+', '-', '*', '/') separated by some number of spaces.", "s represents a valid expression.", "All the integers in the expression are non-negative integers in the range [0, 2^31 - 1].", "The result is guaranteed to fit in a 32-bit integer."]