반응형
문제
https://www.acmicpc.net/problem/1935
1935번: 후위 표기식2
첫째 줄에 피연산자의 개수(1 ≤ N ≤ 26) 가 주어진다. 그리고 둘째 줄에는 후위 표기식이 주어진다. (여기서 피연산자는 A~Z의 영대문자이며, A부터 순서대로 N개의 영대문자만이 사용되며, 길이
www.acmicpc.net
풀이
const fs = require("fs");
const filePath = process.platform === "linux" ? "/dev/stdin" : "./input.txt";
let [N, ex, ...input] = fs.readFileSync(filePath).toString().trim().split("\n");
const nums = input.map(Number);
const stack = [];
let expression = [];
for (let ch of ex) {
if (/[A-Z]/.test(ch)) {
expression.push(nums[ch.charCodeAt(0) - 65]);
} else {
expression.push(ch);
}
}
function calculate(num1, num2, operator) {
const first = +num1;
const second = +num2;
if (operator === "+") return first + second;
else if (operator === "-") return first - second;
else if (operator === "*") return first * second;
else if (operator === "/") return first / second;
}
for (const current of expression) {
// 연산자인 경우
if (["+", "-", "*", "/"].includes(current)) {
const num1 = stack.pop();
const num2 = stack.pop();
stack.push(calculate(num2, num1, current));
} else {
// 숫자인 경우
stack.push(current);
}
}
console.log(stack[0].toFixed(2));
반응형
'Algorithm > BOJ' 카테고리의 다른 글
[알고리즘/백준/10866] 덱(Nodejs, 자료구조) (0) | 2023.06.15 |
---|---|
[알고리즘/백준/10798] 세로읽기 (0) | 2023.06.15 |
[알고리즘/백준/1966] 프린터 큐(Nodejs, 자료구조) (0) | 2023.06.14 |
[알고리즘/백준/16234] 인구이동(Nodejs, BFS) (0) | 2023.06.13 |
[알고리즘/백준/17626] Four Squares(Nodejs, DP) (0) | 2023.06.13 |