본문 바로가기
알고리즘/백준

백준 1436번 - 영화감독 숌 (Java 8)

by latissimus 2022. 3. 1.

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

 

1436번: 영화감독 숌

666은 종말을 나타내는 숫자라고 한다. 따라서, 많은 블록버스터 영화에서는 666이 들어간 제목을 많이 사용한다. 영화감독 숌은 세상의 종말 이라는 시리즈 영화의 감독이다. 조지 루카스는 스타

www.acmicpc.net

1. 처음 푼 코드 -> 빈 문자열 더해서 String 변환 후 contains("666")으로 포함 여부 확인

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class Main {

    public static void main(String[] args) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        int N = Integer.parseInt(br.readLine());
        int count = 0;
        int answer = 0;
        for(int i=666;;i++){
            if((i+"").contains("666")){
                count++;
            }
            if(count == N){
                answer = i;
                break;
            }
        }
        System.out.println(answer);
    }
}

 

2. 수정 - String변환 없이 while문으로 숫자 상태로 직접 분해

속도 324ms -> 120ms

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class Main {
    public static int getTitle666(int N){
        int count = 0;
        int answer = 0;
        
        for(int i=666;;i++){
            int count6 = 0;
            int temp = i; //i값 변질을 막기 위해 temp 사용
            answer =i; //666발견시 데리고갈 값 저장
            
            while (temp != 0) {
                if(temp%10 == 6){ //6이 들어갈때마다 count6++, 연속 세번 6이 있어야 count가 올라간다.
                    count6++;
                } else{
                    count6 = 0; //해당 숫자 6아니면 0으로 초기화
                }
                temp/=10;
                if(count6 == 3){ //6이 연속 3번 발견 시 count++하고 while 탈출
                    count++;
                    break;
                }
            }
            
            if(count == N){ //입력 받은 N과 count가 일치하면 for 탈출
                break;
            }
        }
        return answer;
    }
    public static void main(String[] args) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        int N = Integer.parseInt(br.readLine());
        int answer = getTitle666(N);
        System.out.println(answer);
    }
}

 

3. 탐색 범위를 줄이고 contain을 사용한 방법 - 알고리즘을 정리해서 잘 올려주시는 st님 블로그에서는 666의 위치를 기준으로 탐색범위를 크게 줄여준 방법을 사용했다. 

댓글