반응형
문제
https://www.acmicpc.net/problem/1935
풀이
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 |