Leetcode 150 Evaluate Reverse Polish Notation
Evaluate Reverse Polish Notation – LeetCode
You are given an array of strings tokens that represents an arithmetic expression in a Reverse Polish Notation.
We will use stacks to solve this problem.
- Whenever we see a number, we push it into the stack
- Once we see an operator, we retrieve the last two elements in the stack and calculate the result, and push the result back again.
A couple tricky thing to note:
- Add parenthesis when doing the operation on 2 numbers, so instead of
2--2
which will yield errors we have(2)-(-2)
truncates toward zero
needs some check base on whether the result is positive of negative
Solution
/**
* @param {string[]} tokens
* @return {number}
*/
var evalRPN = function(tokens) {
if(tokens.length === 1) {
return tokens[0]
}
let stack = [];
let result;
for(let i = 0; i < tokens.length; i++) {
if(Number.isInteger(parseInt(tokens[i]))) {
stack.push(tokens[i])
} else {
const token1 = stack.pop();
const token2 = stack.pop();
let temp = eval(`(${token2})${tokens[i]}(${token1})`)
result = temp >= 0 ? Math.floor(temp) : Math.ceil(temp)
stack.push(result)
}
}
return result;
};