CodingTest
[CodingTest] 백준 10773번
동그리담
2024. 4. 9. 11:50
문제를 보고 고민하다가 스택을 떠올렷다.
0이 들어오면 pop을 해서 지우도록 하면 편하게 코딩할 수 있을것이다.
해당 내용을 바탕으로 코딩하면
import java.util.Scanner;
import java.util.Stack;
public class Main{
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
Stack<Integer> stack = new Stack<>();
int repeat_count = sc.nextInt();
int sum=0;
for (int i = 0; i < repeat_count; i++) {
int n = sc.nextInt();
if (!numIsZero(n)) {
stack.pop();
} else {
stack.push(n); //0이 아니면 push
}
}
while (!stack.isEmpty()) {
sum+=stack.pop();
}
System.out.println(sum);
}
static boolean numIsZero(int n){
if(n==0){
return false;
}
return true;
}
}
컬렉션을 사용하면 시간을 많이 쓰게되므로 추후에는 컬렉션을 사용안하고 구현하는 것이 좋을 것 같다!!