-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpostfix.js
65 lines (60 loc) · 1.61 KB
/
postfix.js
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
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
/**
* @desc problem : 후위식 연산 (postfix)
* @desc site : Olympiad
* @desc level: 3
* @desc solution : stack
*/
/**
* 계산 함수
*/
const calculator = {
add: function (left, right) {
return left + right;
},
sub: function (left, right) {
return left - right;
},
div: function (left, right) {
return left / right;
},
mul: function (left, right) {
return left * right;
}
};
/**
* solution
* @param {array} str : 연산식 문자열
*/
function solution(str) {
const operator = ['+', '-', '*', '/'];
const strArray = str.split('');
const operatorStack = [];
strArray.forEach(function (item, index) {
if (operator.includes(item)) {
const right = operatorStack.pop();
const left = operatorStack.pop();
switch (item) {
case '+':
operatorStack.push(calculator.add(left, right));
break;
case '-':
operatorStack.push(calculator.sub(left, right));
break;
case '*':
operatorStack.push(calculator.mul(left, right));
break;
case '/':
operatorStack.push(calculator.div(left, right));
break;
default:
console.log('잘못된 연산');
break;
}
} else {
operatorStack.push(Number(item));
}
});
return operatorStack.pop();
}
const answer = solution('352+*9-'); //12
console.log(answer);