백준 1935번 후위 표기식2

김두현·2022년 10월 26일
2

백준

목록 보기
8/133
post-thumbnail

🔒[문제 url]

https://www.acmicpc.net/problem/1935


🪄전체 코드

#define _CRT_SECURE_NO_WARNINGS
#include <iostream>
#include <string>
#include <algorithm>
#include <cmath>
#include <queue>
#include <vector>
#include <stdio.h>
#include <ctime>
#include <memory.h> // memset
#include <numeric>
#include <stack>
#include <sstream>
using namespace std;
/* –2,147,483,648 ~ 2,147,483,647 */

int n;
string expression;
// 소수를 출력해야하니 double
stack<double> op;
int value[26];

void INPUT()
{
	ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0);
	cin >> n >> expression;
	for (int i = 0; i < n; i++) cin >> value[i];
}



void SOLVE()
{
	for (int i = 0; i < expression.length(); i++)
	{
		char ex = expression[i];

		// ascii code 이용하여 indexing
		if (ex >= 'A' && ex <= 'Z') op.push(value[ex - 'A']);
		else // 연산자
		{
			// 연산에 쓰일 숫자 두 개 pop
			double first = op.top();
			op.pop();
			double second = op.top();
			op.pop();

			// 연산자에 따라 계산
			if (ex == '+') op.push(second + first);
			else if (ex == '-') op.push(second - first);
			else if (ex == '*') op.push(second * first);
			else if (ex == '/') op.push(second / first);
			
		}
	}
	// fixed 사용하면 소수점 아래 자릿수 고정, 안 하면 전체 자릿수 고정
	cout << fixed;
    // precision()함수로 둘째자리수까지만 출력
	cout.precision(2);
	cout << op.top();
    /*만일 이후 소수 자릿수 고정을 해제하고싶다면,
    cout.unsetf(ios::fixed);
    를 이용한다.
    */
}

int main()
{
	INPUT();

	SOLVE();
}

🥇문제 후기

GOLD5 미만 난이도는 알고리즘 및 풀이 설명을 주석으로 대체합니다.
주석을 참고해주세요.


💕오류 지적 및 피드백은 언제든 환영입니다. 복제시 출처 남겨주세요!💕
profile
I AM WHO I AM

2개의 댓글

comment-user-thumbnail
2022년 10월 28일

문제 후기가 괜히 간지나 보이네요... 🤩 항상 멋진 모습 감사드립니다

1개의 답글