
입력횟수인 K를 입력한다. K만큼 숫자를 입력 할 기회가 주어지고 입력된 숫자는 stack에 저장됨.
사용자가 '0' 을 입력할 경우 스택에서 가장 최근에 삽입된 원소를 제거한다.
마지막엔 스택에 있는 모든 원소의 합을 계산하여준다.
import java.util.Scanner;
import java.util.Stack;
public class Zero {
public static void main(String[] args) {
//0을 입력받으면 최근에 입력받았던 수를 지우면 된다.
Scanner sc = new Scanner(System.in);
Stack<Integer> stack = new Stack<Integer>();
int K = sc.nextInt();
int sum = 0;
for(int i = 0; i<K; i++){
int num = sc.nextInt();
if (num == 0){
stack.pop();
}
else {
stack.add(num);
}
}
for (int zero : stack){
sum += zero;
}
System.out.println(sum);
}
}
import java.util.Scanner;
public class Zero_1 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int top = -1;
int K = sc.nextInt();
int arr [] = new int[K];
for(int i = 0; i<K; i++){
int num = sc.nextInt();
//0 = 3 현재 top은 0임 -> 0 들어왔어 top을 -1로 만들어줘야 함 그럼 어차피 합을 구할 때 top가지 계산
if(num == 0){
top--;
}
else {
top++;
arr[top] = num;
}
}
int sum = 0;
for(int i = 0; i<=top; i++){
sum += arr[i];
}
System.out.println(sum);
}
}
top 을 -1로 초기화한다.
마찬가지로 0이 들어오면 top을 감소시켜주고 아닌 경우에는 top을 먼저 증가시켜주고 arr[top] 에 원소를 입력.
0부터 top 까지 for문을 반복하면서 합을 계산해주고 출력한다.