Skip to content

Instantly share code, notes, and snippets.

@acedesigns
Last active November 6, 2020 12:05
Show Gist options
  • Save acedesigns/4be09b8602febcdc629d78c75eb5b084 to your computer and use it in GitHub Desktop.
Save acedesigns/4be09b8602febcdc629d78c75eb5b084 to your computer and use it in GitHub Desktop.
Reverse Polish notation - A javascript Solution
function reversePolish(newExpr) {
let expr = newExpr.split(" ");
let stack =[];
if(expr === ''){
return 0;
}
for(let i=0; i<expr.length; i++) {
if(!isNaN(expr[i]) && isFinite(expr[i])) {
stack.push(expr[i]);
}else {
let a = stack.pop();
let b = stack.pop();
if(expr[i] === "+") {
stack.push(parseInt(a) + parseInt(b));
} else if(expr[i] === "-") {
stack.push(parseInt(b) - parseInt(a));
} else if(expr[i] === "*") {
stack.push(parseInt(a) * parseInt(b));
} else if(expr[i] === "/") {
stack.push(parseInt(b) / parseInt(a));
} else if(expr[i] === "^") {
stack.push(Math.pow(parseInt(b), parseInt(a)));
}
}
}
if(stack.length > 1) {
return "ERROR";
}else {
return stack[0];
}
}
console.log(reversePolish('1 3 5 * -')); // Result: -14
console.log(reversePolish('3 4 + 2 * 1 +')); // Result 15
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment