Basic Calculator II
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).
Sample Input and Output
Example 1 ยท Run Sample
s = "3+2*2" 7 Example 2
s = "14-3/2" 13 - The expression is valid; division never uses a zero divisor.
- All intermediate results fit in a signed 32-bit integer.
Test Cases (2)
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.
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.