Skip to content

Instantly share code, notes, and snippets.

@EnetoJara
Created January 28, 2020 21:05
Show Gist options
  • Save EnetoJara/28dbc82fe0f30d4077203d75737a638e to your computer and use it in GitHub Desktop.
Save EnetoJara/28dbc82fe0f30d4077203d75737a638e to your computer and use it in GitHub Desktop.
Evaluate Reverse Polish Notation in Javascript
/**
Input: [“3”, “1”, “+”, “5”, “*”]
Output: 9
Explanation: ((3 + 1) * 5) = 20
*/
function RPN(seq) {
if (seq.length <= 2) {
console.log('Please enter valid RPN')
return
}
var operands = ['+', '-', '*', '/' ]
var stack = []
var i = 0
stack.push(seq[i])
i++
while(i <= seq.length) {
var item = seq[i]
var index = operands.indexOf(item)
if (index < 0) {
stack.push(seq[i])
} else {
if (index == 0) {
var a = parseInt(stack.splice(-1)[0], 10)
var b = parseInt(stack.splice(-1)[0], 10)
stack.push(a+b)
}
if (index == 1) {
var a = parseInt(stack.splice(-1)[0], 10)
var b = parseInt(stack.splice(-1)[0], 10)
stack.push(b-a)
}
if (index == 2) {
var a = parseInt(stack.splice(-1)[0], 10)
var b = parseInt(stack.splice(-1)[0], 10)
stack.push(a*b)
}
if (index == 3) {
var a = parseInt(stack.splice(-1)[0], 10)
var b = parseInt(stack.splice(-1)[0], 10)
stack.push(b/a)
}
}
i++
}
return parseInt(stack[0],10)
};
console.log(RPN(["2", "1", "+", "3", "*"])) // 9
console.log(RPN(["4", "13", "5", "/", "+"])) // 6
console.log(RPN(["10", "6", "9", "3", "+", "-11", "*", "/", "*", "17", "+", "5", "+"])) // 22
console.log(RPN(["2", "1"])) // Please enter valid RPN undefined
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment