</>

227. Basic Calculator II

Medium
Stack Time O(N) Space O(1)
↗ Open on LeetCode Source: Misc

Quick review

Pattern
Stack
Time
O(N)
Space
O(1)

Standard Solution (C++)

SummaryGiven a string representing an arithmetic expression with non-negative integers and the operators `+`, `-`, `*`, `/` (integer division toward zero), evaluate it and return the integer result — without using any built-in expression evaluator.

Approach
  • Use a stack to handle operator precedence: * and / bind tighter than + and -.
  • Scan the string left to right, accumulating multi-digit numbers; when an operator (or end of string) is encountered, apply the previous operator to the current number.
  • For +/-, push the signed value onto the stack (deferred addition); for *//, pop the stack top, combine it with the current number, and push the result back — this collapses the high-precedence sub-expression immediately.
  • Sum everything remaining on the stack for the final answer. The stack ensures lower-precedence additions are resolved last, naturally implementing standard operator precedence.
#include <string>
#include <stack>
using namespace std;

class Solution {
public:
    int calculate(string s) {
        stack<int> stk;
        int cur = 0;          // current number being parsed
        char op  = '+';       // operator that precedes the current number

        for (int i = 0; i < (int)s.size(); ++i) {
            char c = s[i];

            if (isdigit(c)) {
                cur = cur * 10 + (c - '0');
            }

            // Process when we hit an operator or reach the last character.
            if ((!isdigit(c) && c != ' ') || i == (int)s.size() - 1) {
                if (op == '+') {
                    stk.push(cur);          // push as positive
                } else if (op == '-') {
                    stk.push(-cur);         // push as negative
                } else if (op == '*') {
                    int top = stk.top(); stk.pop();
                    stk.push(top * cur);    // collapse high-precedence op
                } else if (op == '/') {
                    int top = stk.top(); stk.pop();
                    stk.push(top / cur);    // integer division (truncates toward zero)
                }
                op  = c;   // remember operator for next number
                cur = 0;
            }
        }

        // Sum all deferred additions/subtractions on the stack.
        int result = 0;
        while (!stk.empty()) {
            result += stk.top();
            stk.pop();
        }
        return result;
    }
};
Time O(n) Space O(n)

A canonical reference solution. Problem statement © LeetCode — see the official link above.

My Solution (C++)

#include <string>
using namespace std;

class Solution {
public:
    int calculate(string s) {
        long long res=0;
        long long cur=0;
        long long last=0;
        char op='+';

        for(int i=0; i<s.length(); ++i){
            char c=s[i];
            if(isdigit(c)){
                cur=cur*10+(c-'0');
            }

            if(c=='+' || c=='-' || c=='*'|| c=='/' || i==s.length()-1){
                if(op=='+'){
                    res+=last;
                    last=cur;
                }
                else if(op=='-'){
                    res+=last;
                    last=-cur;
                }
                else if(op=='*'){
                    last*=cur;
                }
                else if(op=='/'){
                    last/=cur;
                }
                cur=0;
                op=c;
            }
        }

        res+=last;

        return res;
    }
};

// Time Complexity: O(N)
// Space Complexity: O(1)
Time O(N) Space O(1)

My own solution and notes, as I wrote them.

▶ Run it — editable in-browser playground with a sample driver C++

Your solution plus an auto-generated main() and sample input so Run produces output. The driver and inputs are unverified — edit freely; Reset restores this starting point.

C++ ▶ Runnable Auto-generated driver with sample input — unverified.

Runs in a free public sandbox (Wandbox). Output and timing include network latency; don't paste secrets.

Related — same pattern