백준 10773 제로 JAVA

해버니·2022년 6월 8일
0

백준

목록 보기
6/11

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

스택에 관한건가..




두가지 방법으로 풀었다.
첫번째는 자체 스택?
두번째는 자바에 있는 스택 이용해서

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class Main {
	public static void main(String args[]) throws IOException {
		BufferedReader bf=new BufferedReader(new InputStreamReader(System.in));
		int N=Integer.parseInt(bf.readLine());
		int[] arr=new int[N];
		int input;
		int top=-1;
		for(int i=0;i<N;i++) {
			input=Integer.parseInt(bf.readLine());
			
			if(input==0) {
				arr[top]=0;
				top--;
			} 
			else {
				top++;
				arr[top]=input;
			}
		}
		
		int sum=0;
		
		for(int i=0;i<arr.length;i++) {
			sum+=arr[i];
		}
		
		System.out.println(sum);
	}
}

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Stack;


public class Main {
	public static void main(String args[]) throws IOException {
		BufferedReader bf=new BufferedReader(new InputStreamReader(System.in));
		Stack<Integer> zero=new Stack<>();
		
		int N=Integer.parseInt(bf.readLine());
		int[] arr=new int[N];
		int input;
		int top=-1;
		for(int i=0;i<N;i++) {
			input=Integer.parseInt(bf.readLine());
			
			if(input==0) {
				zero.pop();
			} 
			else {
				zero.push(input);
			}
		}
		
		int sum=0;
		
		while(true) {
			if(zero.empty()==true) {
				break;
			}
			else {
				sum+=zero.pop();
			}
		}
		
		System.out.println(sum);
	}
}

0개의 댓글