Skip to problem
←

Basic Calculator II

Medium 0 attempts

You're given a string s that holds a basic arithmetic expression made up of non-negative integers and the operators +, -, *, and /, with standard operator precedence (multiplication and division happen before addition and subtraction) and no parentheses anywhere. Evaluate the expression and return the result, truncating any division toward zero. Operators of equal precedence are evaluated from left to right. The input is guaranteed to be a valid expression.

Edge cases: The string may contain spaces between tokens, but not within a number. Operators are binary; there are no unary signs. It may be a single number with no operators at all. Division truncates rather than rounds (e.g., 14 / 3 = 4).

Function contract

Implement calculate(s), where s is a valid expression of non-negative integer operands, binary +, -, *, / operators, and optional spaces between tokens.

Output: The integer result using standard precedence, left-to-right evaluation for equal-precedence operators, and division truncated toward zero.

Example 1

Input
s = "3+2*2"
Output
7

Example 2

Input
s = "14-3/2"
Output
13
Constraints
  • 1 <= s.length <= 3 * 10^5
  • Operands are integers from 0 to 2^31 - 1.
  • The expression is valid; operators are binary and division never uses a zero divisor.
  • All intermediate results fit in a signed 32-bit integer.

Approach: Stack with Operator Precedence

Scan left to right, building up each number. When you hit an operator (or the end), apply the previous operator: push for +/-, but pop-and-compute for *// so multiplication and division are handled before addition and subtraction. Sum the stack at the end.

javascript
function calculate(s) {
  const stack = [];
  let num = 0;
  let op = '+';

  for (let i = 0; i <= s.length; i++) {
    const ch = s[i];
    if (ch >= '0' && ch <= '9') {
      num = num * 10 + (ch - '0');
    } else if (ch === '+' || ch === '-' || ch === '*' || ch === '/' || i === s.length) {
      if (op === '+') stack.push(num);
      else if (op === '-') stack.push(-num);
      else if (op === '*') stack.push(stack.pop() * num);
      else if (op === '/') stack.push(Math.trunc(stack.pop() / num));
      op = ch;
      num = 0;
    }
  }
  return stack.reduce((a, b) => a + b, 0);
}

Time Complexity: O(n)

Space Complexity: O(n) for the stack

Loading discussion…

Saved in this browser only. Private to you.

JavaScript