Problem Solving
[백준/Java] 2292번 - 벌집
Jintiago
2022. 4. 3. 19:48
// 6 > 12 > 18 > 24 > ...
// 가운데에서 n 칸 밖으로 갈 때마다 해당 라인의 cell 수는 6n 씩 증가
// 1 : 1 번 이동
// 2 ~ 7 : 2 번 이동
// 8 ~ 19 : 3 번 이동
// 20 ~ 37 : 4 번 이동
import java.util.Scanner;
public class Main{
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int N = sc.nextInt(); // 가고자 하는 cell 번호
int i = 0;
int num = 1;
while (true) {
num = num + 6*i; // i의 증가에 따라 1, 7, 19, 37, ...
if (N == 1) {
System.out.println(1);
break;
} else if ((num-6*i+1) <= N && N <= num) { // 2~7, 8~19, 20~37, ...
System.out.println(i+1); // 움직이는 횟수
break;
}
i++;
}
}
}
서울에 잠시 다녀오는 길, 아버지께서 임종준비실로 옮기셨다는 소식을 듣고 심란한 상태에서 풀었던 문제다.
C로 풀었을 때.
#include <stdio.h>
int main(){
int room_num, last_room=1, cycle_num=0;
scanf("%d", &room_num);
while(1){
last_room = last_room+cycle_num*6; // last_room : 해당 원의 마지막 방
if(room_num <= last_room){
printf("%d\n", cycle_num+1);
break;
}
cycle_num++;
}
return 0;
}
자바로 풀었을 때 보다 더 간결해졌다. 다시 풀어서 그런가?