728x90
https://www.acmicpc.net/problem/2164
📝 유튜브 풀이
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
'코딩테스트 > [JAVA] 백준' 카테고리의 다른 글
[백준 | JAVA | 2920번] 음계 (0) | 2023.12.19 |
---|---|
[백준 | JAVA | 24444번] 알고리즘 수업 - 너비 우선 탐색 1 (0) | 2023.12.18 |
[백준 | JAVA | 1874번] 스택 수열 (1) | 2023.11.15 |
[백준 | JAVA | 11721번] 열 개씩 끊어 출력하기 (1) | 2023.11.14 |
[백준 | JAVA | 12891번] DNA 비밀번호 (1) | 2023.11.12 |