-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathreverse_polish_notation.js
More file actions
47 lines (38 loc) · 952 Bytes
/
reverse_polish_notation.js
File metadata and controls
47 lines (38 loc) · 952 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
var hash_operations = {
"+" : function (val1, val2) {
return val1 + val2;
},
"-" : function (val1, val2) {
return val1 - val2;
},
"*" : function (val1, val2) {
return val1 * val2;
},
"/" : function (val1, val2) {
return val1 / val2;
}
};
function EvaluateReversePolishNotation(arr)
{
var stack = [];
for (var i = 0; i < arr.length; i++)
{
// if it's an operator
if (hash_operations.hasOwnProperty(arr[i]))
{
var second_operand = stack.pop();
var first_operand = stack.pop();
var result = hash_operations[arr[i]](first_operand, second_operand);
stack.push(result);
}
else
{
stack.push(parseInt(arr[i],10));
}
}
return stack.pop();
}
var result1 = EvaluateReversePolishNotation(["2", "1", "+", "3", "*"]);
var result2 = EvaluateReversePolishNotation(["4", "13", "5", "/", "+"]);
console.log(result1);
console.log(result2)