-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathreverse_polish.js
More file actions
42 lines (40 loc) · 1.02 KB
/
reverse_polish.js
File metadata and controls
42 lines (40 loc) · 1.02 KB
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
//Implement reverse polish notation
//Using stack
function calculate(strOne){
var str = strOne.split(" ")
var stack = [];
for(var i = 0; i < str.length; i++){
if(!isNaN(str[i])){
stack.push(str[i]);
}
else {
var operand2 = Number(stack.pop());
var operand1 = Number(stack.pop());
switch (str[i]) {
case '+':
stack.push(operand1 + operand2);
break;
case '-':
stack.push(operand1 - operand2);
break;
case '*':
stack.push(operand1 * operand2);
break;
case '÷':
if(operand2 !== 0){
stack.push(Math.floor(operand1 / operand2));
}
break;
case '^':
stack.push(Math.pow(operand1, operand2));
break;
default:
break;
}
}
}
return stack.length > 0 ? stack.pop() : "error";
}
var postfix = '15 7 1 1 + - ÷ 3 * 2 1 1 + + -'
var result = calculate(postfix);
console.log("Result of '", postfix, "' is", result)