알고리즘/백준

백준 1541_잃어버린 괄호

래울 2020. 11. 1. 19:45

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

 

1541번: 잃어버린 괄호

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

www.acmicpc.net

'-' 가 나오면, 그 뒤는 모두 빼기가 가능하다.

 

#include <stdio.h>
int main() {
    int set=0;
    char op;
    int sum, next;
 
    scanf("%d", &sum);
    while (1) {
        scanf("%c", &op);
        scanf("%d", &next); 
 
        if (op == '-') set = 1;
        else if (op != '+') break;
 
        if (set==1) sum -= next;
        else sum += next;
    }
 
    printf("%d", sum);
    return 0;
}