Taene's

[백준] Class3-잃어버린 괄호 C++ 1541번 본문

백준/Class3

[백준] Class3-잃어버린 괄호 C++ 1541번

taene_ 2023. 11. 21. 10:07

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

 

1541번: 잃어버린 괄호

첫째 줄에 식이 주어진다. 식은 ‘0’~‘9’, ‘+’, 그리고 ‘-’만으로 이루어져 있고, 가장 처음과 마지막 문자는 숫자이다. 그리고 연속해서 두 개 이상의 연산자가 나타나지 않고, 5자리보다

www.acmicpc.net

#include <iostream>
#include <string>
using namespace std;

int main()
{
	ios_base::sync_with_stdio(false);
	cin.tie(NULL);

	string a;
	cin >> a;

	int answer = 0;
	bool isMinus = false;
	string num = "";

	for (int i = 0; i <= a.size(); i++)
	{
		if (a[i] == '+' || a[i] == '-' || i == a.size())
		{
			if (isMinus)
			{
				answer -= stoi(num);
				num = "";
			}
			else
			{
				answer += stoi(num);
				num = "";
			}
		}
		else
		{
			num += a[i];
		}

		if (a[i] == '-')
			isMinus = true;
	}

	cout << answer;

	return 0;
};

 

풀이: 식을 입력받고 식이 끝날때까지 숫자가 나오면 num에 저장했다가 +가 나오면 더해주고, -가 나오면 - 뒤의 숫자들을 모두 빼주면 된다.