๋ฌธ์
ํ์ด 1
import java.util.*; class Main { static int n; static Queue<Integer> q; public static void main(String[] args) { Scanner sc = new Scanner(System.in); n = sc.nextInt(); q = new LinkedList<>(); for(int i = 1; i <= n; i++) { q.offer(i); } while(!q.isEmpty()) { try { int num1 = q.poll(); System.out.print(num1 + " "); int num2 = q.poll(); q.offer(num2); } catch(NullPointerException e) { break; } } } }
- ์ฒซ ํ์ด ๋ NullPointer ์ค๋ฅ๊ฐ ๋ฐ์ํด try-catch๋ก ๋ฌธ์ ๋ฅผ ํด๊ฒฐํ์ต๋๋ค.
ํ์ด 2
import java.util.*; class Main { static int n; static Queue<Integer> q; public static void main(String[] args) { Scanner sc = new Scanner(System.in); n = sc.nextInt(); q = new LinkedList<>(); for(int i = 1; i <= n; i++) { q.offer(i); } while(q.size() > 1) { int num1 = q.poll(); System.out.print(num1 + " "); int num2 = q.poll(); q.offer(num2); } System.out.print(q.poll()); } }
- try-catch๋ฌธ์ ์ฐ์ง ์๋ ๊ฒ์ด ๋ ๊ฐ๊ฒฐํ ์ฝ๋์ธ ๊ฑฐ ๊ฐ์ต๋๋ค.
'๐ Coding Test > ๋ฐฑ์ค Sliver' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
[๋ฐฑ์ค 1260] DFS์ BFS | ์๋ฐ (0) | 2024.11.08 |
---|---|
[๋ฐฑ์ค 2805] ๋๋ฌด ์๋ฅด๊ธฐ | ์๋ฐ (0) | 2024.11.04 |