C# 10773번 제로

2022. 2. 9. 16:31C#/[백준] 스택

문제

코드 :

using System;
using System.Collections;
namespace _2
{
    class Program
    {
        static void Main(string[] args)
        {
            int N = Convert.ToInt32(Console.ReadLine());
            int output = 0;
            Stack stack = new Stack();
            for (int i = 0; i < N; i++)
            {
                int num = Convert.ToInt32(Console.ReadLine());
                if (num == 0)
                {
                    stack.Pop();
                }
                else
                    stack.Push(num);                
            }
            //pop할때 stack.count가 실시간으로 줄어들어서
            //정상적인 횟수만큼 돌지 않는다.
            //그래서 따로 변수로 만들어줘야한다.
            int max = stack.Count;
            for (int i = 0; i < max; i++)
            {
                output += Convert.ToInt32(stack.Pop());
            }

            Console.WriteLine(output);
        }
    }
}

입력값으로 0이 들어올때마다 Pop하기만 하고 아니면 Push 해준다. 완성 된 스택을 하나씩 Pop하면서 더해주면 된다.  

'C# > [백준] 스택' 카테고리의 다른 글

C# 17298번 오큰수  (0) 2022.02.15
C# 1874번 스택 수열  (0) 2022.02.15
C# 4949번 균형잡힌 세상  (0) 2022.02.15
C# 9012번 괄호  (0) 2022.02.09
C# 10828번 스택  (0) 2022.02.09