본문 바로가기

Algorithm

1222. [S/W 문제해결 기본] 6일차 - 계산기1

반응형

https://swexpertacademy.com/main/code/problem/problemDetail.do?contestProbId=AV14mbSaAEwCFAYD&categoryId=AV14mbSaAEwCFAYD&categoryType=CODE

 

SW Expert Academy

SW 프로그래밍 역량 강화에 도움이 되는 다양한 학습 컨텐츠를 확인하세요!

swexpertacademy.com

 

 

후위 표기식 만드는법

1. 후위 표기식을 완성시킬 벡터 준비.

2. 연산을 넣을 스택 준비.

3. 숫자면 완성 벡터에 그냥 넣고 연산이면 연산 스택이 비어있는 경우 삽입.

안 비어있는 경우 우선순위에 따라 top 꺼내서 결과 벡터에 넣고 자신은 삽입.

4. 결과 벡터가 만들어 졌으면

값을 출력할 int 스택 준비

5. 숫자면 값 스택에 넣고 연산이면 두개의 값을 꺼내서 연산 수행후에 다시 넣음. 

 

 

#include<iostream>
#include<string>
#include<vector>
#include<stack>

using namespace std;
string str;
int N;

int main(int argc, char** argv)
{
	int test_case;
	

	for (test_case = 1; test_case <= 10; ++test_case)
	{
		
		cin >> N >> str;
		vector<char> result;
		stack<char> sta;

		for (int i = 0; i < N; i++)
		{
			if (str[i]  >= '0' && str[i] <= '9')
			{
				result.push_back(str[i]);
			}
			else
			{
				if (sta.empty())
				{
					sta.push(str[i]);
				}
				else
				{
					result.push_back(sta.top());
					sta.pop();
					sta.push(str[i]);
				}
			}
		}

		while (!sta.empty())
		{
			result.push_back(sta.top());
			sta.pop();
		}

		stack<int> num;

		for (int i = 0; i < result.size(); i++)
		{
			if (result[i] >= '0' && result[i] <= '9')
			{
				num.push(result[i] - '0');
			}
			else
			{
				int a = num.top();
				num.pop();
				int b = num.top();
				num.pop();
				int z = a + b;
				num.push(z);
			}
		}

		cout << "#" << test_case << " " << num.top() << endl;


	}
	return 0;//정상종료시 반드시 0을 리턴해야합니다.
}
반응형