콘솔창 & 윈도우창/코딩 테스트

백준 실버 2 잃어버린 괄호 1541

뽀또치즈맛 2025. 5. 15. 12:41

https://github.com/kwon1232/CodingTest/tree/main/%EB%B0%B1%EC%A4%80/Silver/1541.%E2%80%85%EC%9E%83%EC%96%B4%EB%B2%84%EB%A6%B0%E2%80%85%EA%B4%84%ED%98%B8

 

CodingTest/백준/Silver/1541. 잃어버린 괄호 at main · kwon1232/CodingTest

This is an auto push repository for Baekjoon Online Judge created with [BaekjoonHub](https://github.com/BaekjoonHub/BaekjoonHub). - kwon1232/CodingTest

github.com

 



int main(void)
{
    ios::sync_with_stdio(false);
    cin.tie(NULL);
    std::cout.tie(NULL);

    string str = "", temp = "";
    int result = 0;
    cin >> str;

    bool minus = false;
    for (int i = 0; i <= str.size(); i++)
    {
        // 부호를 만났을 때
        if (str[i] == '+' || str[i] == '-' || str[i] == '\0')
        {
            // 이전 값이 - 였다면 이전 값을 모두 빼준다.
            if (minus) {
                result -= stoi(temp);
            }
            // 이전 값이 -가 아니었다면 모두 더해준다
            else {
                result += stoi(temp);
            }
            // 현재 부호가 - 라면 이전 값이 -가 된다는 걸 알려준다.
            temp = "";
            if (str[i] == '-')
            {
                minus = true;
            }
        }
        // 숫자라면 모두 더해준다.
        else
        {
            temp += str[i];
        }

    }

    cout << result;

    return 0;
}

 

 

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