알고리즘/백준
[boj 1935] 후위 표기식2 -js
jinux127
2022. 3. 9. 17:32
후위 표기식을 일단 검색하였다..
https://woongsios.tistory.com/288(참고)
// 후위 표기식2
const filePath = process.platform === "linux" ? "/dev/stdin" : "input.txt";
const input = require('fs').readFileSync(filePath).toString().trim().split(/\s/);
const N = Number(input.shift());
const expression = input.shift();
const numArr = input.map(Number);
const sol = (N,expression,numArr) =>{
const alphabetObj = {};
const stk = [];
const command = {
'+': (a, b) => a + b,
'-': (a, b) => a - b,
'*': (a, b) => a * b,
'/': (a, b) => a / b,
};
for(let i=0;i<numArr.length;i++){
alphabetObj[String.fromCharCode(65+i)] = numArr[i];
}
for(let i=0; i<expression.length;i++){
if (expression[i] >= 'A') stk.push(alphabetObj[expression[i]]);
else {
const b = stk.pop();
const a = stk.pop();
stk.push(command[expression[i]](a,b));
}
}
console.log(stk[0].toFixed(2));
}
sol(N,expression,numArr);
규칙: 연산자를 만나면 바로 앞 피연산자 두개를 연산한다. 123*- => (2*3)-1
1. 알파벳에 값을 묶어준다.
2. 피연산자의 경우 스택에 값을 넣어준다.
3. 연산자를 만났을 경우 피연산자 두개를 pop 가져와 연산한다.(반복)
객체를 통해 함수를 불러오는 방법 기억하자!