Basic Calculator II
Problem
Given a string s
which represents an expression, evaluate this expression and return its value.
The integer division should truncate toward zero.
You may assume that the given expression is always valid. All intermediate results will be in the range of [-231, 231 - 1]
.
Note: You are not allowed to use any built-in function which evaluates strings as mathematical expressions, such as eval()
.
Example 1:
Input: s = "3+2*2" Output: 7
Example 2:
Input: s = " 3/2 " Output: 1
Example 3:
Input: s = " 3+5 / 2 " Output: 5
Constraints:
1 <= s.length <= 3 * 105
s
consists of integers and operators('+', '-', '*', '/')
separated by some number of spaces.s
represents a valid expression.- All the integers in the expression are non-negative integers in the range
[0, 231 - 1]
. - The answer is guaranteed to fit in a 32-bit integer.
Solution
/**
* @param {string} s
* @return {number}
*/
var calculate = function(s) {
let curNum = 0;
const stack = [];
let operation = "+";
s += "+"; // hack so last value gets calculated and added to stack
for (const c of s) {
if (isDigit(c)) { // c is number
curNum = curNum * 10 + parseInt(c);
} else if (c !== ' ') { // c is next operation
if (operation === "+") {
stack.push(curNum);
} else if (operation === "-") {
stack.push(-1 * curNum);
} else if (operation === "*") {
stack.push(stack.pop() * curNum);
} else {
stack.push(Math.trunc(stack.pop() / curNum));
}
curNum = 0;
operation = c;
}
}
return stack.reduce((cur, acc) => cur + acc, 0);
};
var isDigit = function(c) {
return ('0' <= c && '9' >= c);
};
We have a stack to keep track of all intermediate values, the goal is to have all values in the stack sum up to our desired result. We push values directly into the stack if it's addition or subtraction. We pop the stack first and modify the values using the appropriate operation before we push if it's multiplication or division.