Last active
November 6, 2020 12:05
-
-
Save acedesigns/4be09b8602febcdc629d78c75eb5b084 to your computer and use it in GitHub Desktop.
Reverse Polish notation - A javascript Solution
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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
Explanation
https://dev.to/subinedge/evaluate-reverse-polish-notation-expressions-using-javascript-algorithms-jmb