Koala - 5기/코딩테스트 준비 스터디

[BOJ / JAVA] 2164 - 카드2

김호식 3마리 치킨 2022. 2. 12. 19:45

문제

풀이

간단하게 큐를 이용하여 풀었습니다.

1부터 N까지 큐에 입력한 뒤, 반복문을 실행합니다.

반복문은 2가지의 동작을 연속적으로 합니다.

첫 번째 동작은 큐의 숫자를 poll하여 삭제하는 것이고, 다음 동작은 poll한 숫자를 다시 큐에 add 하는 것 입니다.

이 과정에서 isEmpty() 가 true가 된다면 마지막의 값을 출력하고 종료합니다.

코드

import java.io.*;
import java.util.*;

class Main {
				
	public static void main(String[] args) throws IOException{
		
    	BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
    	BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out));
    	Queue<Integer> q = new LinkedList<>();
    	int N = Integer.parseInt(br.readLine());
    	for(int i=1;i<=N;i++) {
    		q.add(i);
    	}
    	int temp;
    	while(true) {
    		temp = q.poll();
    		if(!q.isEmpty())
    			q.add(q.poll());
    		else break;
    	}
    	
    	bw.write(String.valueOf(temp));
    	
    	bw.flush();
    }
}

결과