Home
DSA Patterns
Stack
Basic Calculator II
Basic Calculator II (LeetCode 227)
Basic Calculator II (LeetCode 227): evaluate an expression with + - * / and no parentheses in one pass: a stack of terms where * and / are applied to the top right away.
Problem Understanding
Basic Calculator II: evaluate a valid expression string containing non-negative integers, +, -, *, / and spaces, with no parentheses. Integer division truncates toward zero. Built-in eval is not allowed.
Example: "3+2*2" returns 7, because 2*2 is done before the addition.
The Intuition: Multiply Now, Add Later
Precedence says * and / bind tighter than + and -. A stack of terms to add handles that in one pass:
- Read digits into
num. - When an operator (or the end) arrives,
numis complete. Look at the operator before it,op:+: pushnum;-: push-num. These wait.*or/: pop the top, combine it withnum, push the result. These happen now.
- Set
opto the new operator and resetnum. - Sum the stack.
Starting with op = '+' makes the first number an ordinary push. Compare Evaluate Reverse Polish Notation, where the order of operations is already spelled out.
Basic Calculator II Visualization
num = 0, op = '+'
s
0
1
2
3
4
terms (stack, top on the right)
EMPTY
num
0
op
+
Answer
:
Empty stack, num = 0, and op = '+' as if the expression started with a plus
Next
Digit 3: num = 3
s
The expression is on top, one character per cell; a space is drawn as ␣. Below it are the terms on the stack. Watch num grow digit by digit, then get pushed or folded into the top when the next operator arrives.
Basic Calculator II Dry Run
Input: "14-3/2"
| Char | num | op before | Action | Stack after |
|---|---|---|---|---|
| 1, 4 | 14 | + | - | [] |
| - | 14 | + | push 14 | [14] |
| 3 | 3 | - | - | [14] |
| / | 3 | - | push -3 | [14, -3] |
| 2 (end) | 2 | / | -3 / 2 = -1 | [14, -1] |
Answer: 14 + (-1) = 13.
Basic Calculator II LeetCode Solution
A stack of terms, the number being read, and the operator in front of it. Java and C need / on ints, which already truncates toward zero; Python and JavaScript truncate explicitly.
Basic Calculator II Code
1var calculate = function(s) {2 const stack = [];3 let num = 0, op = '+';4 for (let i = 0; i < s.length; i++) {5 const c = s[i];6 if (c >= '0' && c <= '9') num = num * 10 + Number(c);7 if ((c !== ' ' && !(c >= '0' && c <= '9')) || i === s.length - 1) {8 if (op === '+') stack.push(num);9 else if (op === '-') stack.push(-num);10 else if (op === '*') stack.push(stack.pop() * num);11 else stack.push(Math.trunc(stack.pop() / num));12 op = c;13 num = 0;14 }15 }16 return stack.reduce((a, b) => a + b, 0);17};
Basic Calculator II in Python, Java, C++, TypeScript and C
Basic Calculator II in Python
class Solution:
def calculate(self, s: str) -> int:
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)Basic Calculator II in Java
class Solution {
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 v : stack) sum += v;
return sum;
}
}Basic Calculator II in C++
class Solution {
public:
int calculate(string s) {
vector<int> stack;
long 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 v : stack) sum += v;
return sum;
}
};Basic Calculator II in TypeScript
function calculate(s: string): number {
const stack: number[] = [];
let num = 0, op = '+';
for (let i = 0; i < s.length; i++) {
const c = s[i];
if (c >= '0' && c <= '9') num = num * 10 + Number(c);
if ((c !== ' ' && !(c >= '0' && c <= '9')) || 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(Math.trunc(stack.pop()! / num));
op = c;
num = 0;
}
}
return stack.reduce((a, b) => a + b, 0);
}Basic Calculator II in C
int calculate(char* s) {
int n = strlen(s), top = 0;
int* stack = malloc(n * sizeof(int));
long num = 0;
char op = '+';
for (int i = 0; i < n; i++) {
char c = s[i];
if (isdigit(c)) num = num * 10 + (c - '0');
if ((!isdigit(c) && c != ' ') || i == n - 1) {
if (op == '+') stack[top++] = num;
else if (op == '-') stack[top++] = -num;
else if (op == '*') stack[top - 1] *= num;
else stack[top - 1] /= num;
op = c;
num = 0;
}
}
int sum = 0;
for (int i = 0; i < top; i++) sum += stack[i];
free(stack);
return sum;
}Edge Cases & Common Mistakes
- Multi-digit numbers: build
numacross characters; do not treat each digit as a number. - Spaces: skip them, but still finish the last number when the string ends in a space or a digit (
i == n - 1). - Negative division:
-3 / 2must be-1. Python's//gives-2; useint(a / b). - Using the current operator: the action belongs to the operator before the number; keep
opone step behind. - Overflow: intermediate products fit in 32 bits for LeetCode's inputs; C++ and C keep
numaslongwhile it is read.
Summary
Read numbers digit by digit. When a number ends, the operator before it decides: push it, push its negation, or fold it into the top with * or /. Only additions remain, so return the sum of the stack. O(n) time, O(n) space, or O(1) with a running total.
More practice: DSA interview questions with answers · patterns cheat sheet
