[백준/BOJ] 1541. 잃어버린 괄호 [SIlver 2]

jychan99·2021년 12월 24일
0
post-thumbnail
  1. 잃어버린 괄호

문제출처 : https://www.acmicpc.net/problem/1541

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

int main()
{
	int result = 0, i;
	string arr;

	cin >> arr;
	string temp;
	bool isMinus = false;

	for (i = 0; i <= arr.length(); i++)
	{
		if (arr[i] == '+' || arr[i] == '-' || i == arr.length())
		{
			if (isMinus)
			{
				result -= stoi(temp);
				temp = "";
			}
			else
			{
				result += stoi(temp);
				temp = "";
			}
		}
		else
			temp += arr[i];

		if (arr[i] == '-')
			isMinus = true;
	}
	
	cout << result;

	return 0;
}

괄호를 치는데, -가 한번오면 그 뒤로 괄호를 쳐주면 모두 뺄셈을 하게되므로 -가 들어오는지 안오는지 bool값을 정해서 안오면 +해주고, 오면 빼주면된다.

문자열을을 정수로 바꾸기 위해서는 stoi()함수(string to int)를 써주면 된다.

참고블로그 : https://scarlettb.tistory.com/64
참고많이했습니다. 감사합니다!

profile
내가 지금 두려워 하고 있는 일이 바로 내가 지금 해야 할 일이다. 🐥

0개의 댓글