Basic Calculator II Medium 0 attempts
LeetCode ↗

Basic Calculator II

Medium StringHash Table LeetCode

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. The input is guaranteed to be a valid expression.

Edge cases: The string may contain spaces anywhere. It may be a single number with no operators at all. Division truncates rather than rounds (e.g., 14 / 3 = 4).

Input Format
Implement calculate(s). Inputs below show JavaScript function arguments; there is no stdin parsing.
Output Format
Return the result described in the statement.

Sample Input and Output

Example 1 ยท Run Sample

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

Example 2

Input
s = "14-3/2"
Output
13
Constraints
  • The expression is valid; division never uses a zero divisor.
  • All intermediate results fit in a signed 32-bit integer.
Test Cases (2)
Case 1
Args: ["3+2*2"] Expected: 7
Case 2
Args: ["14-3/2"] Expected: 13

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

Saved in this browser only. Private to you.

JavaScript