[백준 | JAVA | 2164번] 카드2

728x90

 

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

 

 

📝 유튜브 풀이

https://www.youtube.com/watch?v=Cu4LHfjE4ek

import java.util.LinkedList;
import java.util.Queue;
import java.util.Scanner;

public class Main {
 
	public static void main(String[] args) {
		/*첫 번째 카드는 버린다.
		  두 번쨰 카드는 가장 아래 있는 카드 밑으로 옮긴다.
		  이것을 무한 반복하다가 카드가 한장 남으면 출력한다.
		  큐의 선입선출 성질을 이용하면 쉽게 구현 가능 */
		
		Scanner scanner = new Scanner(System.in);
		
		Queue<Integer> myQueue = new LinkedList<>();
		
		int N = scanner.nextInt();
		
		for(int i=1; i<=N; i++) {
			myQueue.add(i);
		}
		
		while (myQueue.size()>1) {
			myQueue.poll();
			myQueue.add(myQueue.poll());
		}
		System.out.println(myQueue.poll());
	}
}



📝 나의 풀이

import java.io.IOException;
import java.util.LinkedList;
import java.util.Queue;
import java.util.Scanner;

public class Main {
 
	public static void main(String[] args) throws IOException {
		Scanner scanner = new Scanner(System.in);
		
		//N장의 카드 
		int N = scanner.nextInt();
		
		//큐 생성 
		Queue<Integer> queue = new LinkedList<>();
		
		for(int i=1; i<=N; i++) {
			//큐에 집어넣는다.
			queue.offer(i);
		}
		
		// 큐 사이즈가 1이 될때까지 반복 
		while (1<queue.size()) {
			
			//큐에서 뺴낸 다음 
			queue.poll();
			
			// 다음 값을 큐에 다시 넣어 가장 아래에 넣어준다..
			queue.offer(queue.poll());
		}
		System.out.println(queue.poll());
	}
}
 
728x90