[백준] 후위 표기식2 #1935

welchs·2022년 1월 12일
0

알고리즘

목록 보기
8/44
post-thumbnail

설명

후위 표기식에 대한 정확한 계산법은 구글링을 통해 알았다.
스택을 이용하면 될꺼라 아이디어가 떠올랐고 JS는 일반 배열을 스택으로 사용해서 풀고, C++은 제공하는 stack 자료구조를 활용했다.
JS 풀이의 경우 eval 함수를 통해 연산식을 바로 계산할 수 있다는 점이 편했지만 현업에서는 쓸일이 없는 함수라 이걸 사용해서 푸는게 맞나 싶었다.

C++에서는 어쩔 수 없이 연산자에 대한 계산을 조건문을 통해 나눠서 계산해주었다.

Node.js 풀이

const fs = require('fs');
const input = fs.readFileSync('/dev/stdin').toString().trim().split('\n');

const N = Number(input[0]);
const data = input[1];
const nums = input.slice(2).map(Number);

const solution = (N, data, nums) => {
  const stack = [];
  const alphabets = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
  for (const x of data) {
    if (alphabets.includes(x)) {
      stack.push(nums[alphabets.indexOf(x)]);
    } else {
      const n2 = stack.pop();
      const n1 = stack.pop();
      const result = eval(`${n1}${x}${n2}`);
      stack.push(result);
    }
  }
  return stack.pop().toFixed(2);
};

console.log(solution(N, data, nums));

C++ 풀이

#include <bits/stdc++.h>
using namespace std;

int main() {
    ios::sync_with_stdio(0);
    cin.tie(0);
    int N; cin >> N;
    string data; cin >> data;
    vector<int> nums(N);
    for (int i=0; i<N; i++) {
        cin >> nums[i];
    }
    
    stack<double> S;
    for (int i=0; i<data.length(); i++) {
        if ('A' <= data[i] && data[i] <= 'Z') {
            S.push(nums[data[i] - 'A']);
        } else {
            double n1, n2;
            n2 = S.top(); S.pop();
            n1 = S.top(); S.pop();
            if (data[i] == '+') S.push(n1 + n2);
            else if (data[i] == '-') S.push(n1 - n2);
            else if (data[i] == '*') S.push(n1 * n2);
            else if (data[i] == '/') S.push(n1 / n2);
        }
    }
    cout << fixed;
    cout.precision(2);
    cout << S.top() << '\n';
    return 0;
}
profile
고수가 되고 싶은 조빱

0개의 댓글