Algorithm/BOJ

[알고리즘/백준/1935] 후위 표기식2(Nodejs, 자료구조)

개발자 김비숑 2023. 6. 14. 23:55
반응형

문제


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));

 

반응형