본문 바로가기
Algorithm/BOJ

[백준/BOJ] 1541번 - 잃어버린 괄호 (C++)

by shine-jung 2022. 3. 21.
반응형

문제 링크


코드

#include <bits/stdc++.h>
using namespace std;

int main(void) {
    ios::sync_with_stdio(0);
    cin.tie(0);
    string s;
    cin >> s;
    int result = 0, n = 0;
    char op = '+';
    for (auto c : s) {
        if (c >= '0' && c <= '9')
            n = n * 10 + (c - '0');
        else {
            if (op == '+') result += n;
            if (op == '-') result -= n;
            if ( c == '-') op = '-';
            n = 0;
        }
    }
    if (op == '+') result += n;
    if (op == '-') result -= n;
    cout << result;
}



설명


문자열 순회가 끝난 후 마지막 숫자 케이스도 처리해줘야 한다.




(주의) 기록용으로 작성한 글입니다. 좋은 코드가 아닐 수 있습니다.

댓글 환영합니다!


반응형

댓글