Algo-Sim › Stacks & Monotonic Stack

Basic Calculator II

Medium · Stacks & Monotonic Stack · step through it in Java, Python and C++ on your own input

Evaluate + − × ÷ without eval: a pending operator decides whether the next number is pushed as a term or folded into the top.

Problem

Evaluate the string s, an expression of non-negative integers, +, -, *, / and spaces, and return its integer value. Multiplication and division bind tighter than addition and subtraction, and division truncates toward zero. Built-in expression evaluators are not allowed.

Constraints

Edge cases to test

Follow-up questions

Can you avoid the stack?
Keep the running total and the last term: +/− add the last term to the total, ×/÷ fold into the last term. O(1) space.
How do you add parentheses?
Recurse on each ( (or push the state on a stack) and treat the result as a number: Basic Calculator III (LC 772).

Solution

Java

public int calculate(String s) {
    Deque<Integer> stack = new ArrayDeque<>();
    int num = 0;
    char op = '+';
    for (int i = 0; i < s.length(); i++) {
        char c = s.charAt(i);
        if (Character.isDigit(c)) num = num * 10 + (c - '0');
        if ((!Character.isDigit(c) && c != ' ') || i == s.length() - 1) {
            if (op == '+') stack.push(num);
            else if (op == '-') stack.push(-num);
            else if (op == '*') stack.push(stack.pop() * num);
            else stack.push(stack.pop() / num);
            op = c;
            num = 0;
        }
    }
    int sum = 0;
    for (int x : stack) sum += x;
    return sum;
}

Python

def calculate(s):
    stack, num, op = [], 0, '+'
    for i, c in enumerate(s):
        if c.isdigit(): num = num * 10 + int(c)
        if (not c.isdigit() and c != ' ') or i == len(s) - 1:
            if op == '+': stack.append(num)
            elif op == '-': stack.append(-num)
            elif op == '*': stack.append(stack.pop() * num)
            else: stack.append(int(stack.pop() / num))
            op, num = c, 0
    return sum(stack)

C++

#include <bits/stdc++.h>
using namespace std;

class Solution {
  public:
    int calculate(string s) {
        vector<int> stack = {};
        int num = 0;
        char op = '+';
        for (int i = 0; i < (int)s.size(); i++) {
            char c = s[i];
            if (isdigit(c)) num = num * 10 + (c - '0');
            if ((!isdigit(c) && c != ' ') || i == (int)s.size() - 1) {
                if (op == '+') stack.push_back(num);
                else if (op == '-') stack.push_back(-num);
                else if (op == '*') stack.back() *= num;
                else stack.back() /= num;
                op = c;
                num = 0;
            }
        }
        int sum = 0;
        for (int x : stack) sum += x;
        return sum;
    }
};

More Stacks & Monotonic Stack problems