Basic Calculator II Visualizer & Step-by-Step Algorithm Solution

Evaluate an arithmetic expression string containing non-negative integers, '+', '-', '*', '/', and spaces with standard operator precedence using an operand stack.

Category: stack | Difficulty: Medium

Tags: Stack, Math, String, Arithmetic Evaluation

Basic Calculator II

Expression String (s)
3
0
+
1
2
2
*
3
2
4
Push / Pop (Top)
(Empty Stack)
Operand Stack (LIFO)
100%
state
i-
char-
num0
sign'+'
stackTop-
stackSize0
Initialization
1/10
Explanation

Initialize calculator for expression "3+2*2". Stack is empty, num = 0, initial sign = '+'.

Source Code
1function calculate(s) {
2 const stack = [];
3 let num = 0;
4 let sign = '+';
5 for (let i = 0; i < s.length; i++) {
6 const c = s[i];
7 if (c >= '0' && c <= '9') {
8 num = num * 10 + Number(c);
9 }
10 if ((c !== ' ' && (c < '0' || c > '9')) || i === s.length - 1) {
11 if (sign === '+') stack.push(num);
12 else if (sign === '-') stack.push(-num);
13 else if (sign === '*') stack.push(stack.pop() * num);
14 else if (sign === '/') stack.push(Math.trunc(stack.pop() / num));
15 sign = c;
16 num = 0;
17 }
18 }
19 return stack.reduce((a, b) => a + b, 0);
20}