본문 바로가기
백준 풀이

[백준 풀이_Java] 0000 약수구하기

by happyhelen 2021. 11. 1.

 

 

 

처음 생각

 

보자마자 이건 스택이다! 라고 생각했다

 

그리고 스택 사용할 때는 스택 안에 값이 남아있는지 없는지 확인하는 것에 유의하자!

 

 

 

 

내가 푼 방법

 

import java.util.Scanner;
import java.util.Stack;

public class Main {

	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);
		int T = sc.nextInt();
		Stack<Integer> number = new Stack<>();
		int total=0;
		
		for(int i=0 ;i <T; i++) {
			int num = sc.nextInt();
			if(num == 0 && !number.isEmpty()) {
				number.pop();
			}
			else {
				number.add(num);
			}
		}
		for(int a : number) {
			total += a;
		}
		System.out.println(total);

	}

}