[C/Python] 백준 10773번 - 제로

매미·2024년 7월 4일

백준

목록 보기
11/15
post-thumbnail

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

문제

발상

< Python >
입력 값이 0이면 list에서 가장 끝에 있는 값을 pop하고 그 이외에는 입력 값을 list에 추가한 후, 합산.
< C언어 >
배열의 크기를 나타내는 변수인 cnt를 만들고,
입력 값이 0이면 cnt에서 1을 빼고 다시 입력을 받아 덮어씌움. 그 이외에는 입력 값을 배열에 추가한 후, 합산.

Clang

#include <stdio.h>

int main() {
    int n, input;
    scanf("%d", &n);
    
    int arr[n];
    int cnt=0;
    
    for (int i=0; i<n; i++) {
        scanf("%d", &input);
        if (input==0) {
            cnt--;
        }
        else {
            arr[cnt]=input;
            cnt++;
        }
    }

    int sum=0;
    for (int i=0; i<cnt; i++)
        sum+=arr[i];
    
    printf("%d", sum);
    return 0;
}

Python

import sys
n = int(sys.stdin.readline())
list = []
for _ in range(n):
    input = int(sys.stdin.readline())
    if input == 0 :
        list.pop(-1)
    else:
        list.append(input)
print(sum(list))
profile
Kwangwoon Univ. Computer Information and Engineering 24

0개의 댓글