C언어

백준 1935번 boj 후위 표기식2 : stack 써서 calculate number!

mcdn 2020. 8. 18. 15:58
반응형

#include <iostream>
#include <stack>
#include <cstring>
using namespace std;

int alphaarr[26];
stack <double> st;

double calnum(double num1, double num2, char op)
{
	if (op == '+')
		return num1 + num2;
	else if (op == '-')
		return num1 - num2;
	else if (op == '*')
		return num1 * num2;
	else if (op == '/')
		return num1 / num2;
}

int main(void)
{
	int n;
	cin >> n; //5
	char str[101];
	cin >> str; //ABC*+DE/-
	for (int i = 0; i < n; i++)
		cin >> alphaarr[i];
	int len = strlen(str);
	double num1, num2;
	for (int i = 0; i < len; i++)
	{
		if (str[i] >= 'A' && str[i] <= 'Z')
			st.push((double)alphaarr[str[i] - 'A']);
		else
		{
			num2 = st.top();
			st.pop();
			num1 = st.top();
			st.pop();
			st.push(calnum(num1, num2, str[i]));
		}
	}
	printf("%.2f", st.top());
}

한번에 통과! 

 

반응형