후위 표기식을 일단 검색하였다..
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 가져와 연산한다.(반복)
객체를 통해 함수를 불러오는 방법 기억하자!
'알고리즘 > 백준' 카테고리의 다른 글
[boj 2193] 이친수 (0) | 2022.03.11 |
---|---|
[boj 10808] 알파벳 개수 -js (0) | 2022.03.10 |
[boj 17299] 오등큰수 - js (0) | 2022.03.09 |
[boj 17298] 오큰수 - js (0) | 2022.03.09 |
[boj 10866] 덱 -js (0) | 2022.03.09 |