[JS/Programmers] 43238. 입국심사

정나린·2023년 3월 23일
1

💬 문제

문제 난이도: Programmers Lv.3

문제 링크: https://school.programmers.co.kr/learn/courses/30/lessons/43238

❗️접근방법

이분탐색

👆 1차 코드(통과❌ - 런타임 에러)

function BinarySearch(min, max, times, n){
    if (min === max) return min;
    
    const mid =((max+min)/2) >> 0;
    let temp = 0;
    for (const time of times){
        temp += (mid/time)>>0;
        
    }
    if (temp >=n) return BinarySearch(min, mid, times, n);
    else return BinarySearch(mid+1, max, times, n);
}
function solution(n, times) {
    return BinarySearch(0, Math.max(...times)*n, times, n);
}

런타임 에러 원인
소수점 이하 부분을 잘라내기 위해 >> 연산을 쓰는 방식에서 에러가 발생했다.
times 배열의 최댓값은 1000000000 이고 n의 최댓값은 1000000000이다.
그런데 >> 연산은 signed 32-bit 정수 범위 내에서만 가능하다.
즉, solution 함수에서 BinrarySearch 함수가 호출될 때 두번째 인수의 크기가 너무 커지면 >> 연산으로 원하는 결과가 나오지 않을 수 있고 몇몇 테스트 케이스에서 에러가 발생하게 된다.

✌️ 2차 코드(통과✅ - 다른 사람 풀이 참고)

function BinarySearch(min, max, times, n){
    if (min === max) return min;
    
    const mid =Math.floor((min+max)/2);
    let temp = 0;
    for (const time of times){
        temp += Math.floor(mid/time);
    }
    if (temp >=n) return BinarySearch(min, mid, times, n);
    else return BinarySearch(mid+1, max, times, n);
}



function solution(n, times) {
    return BinarySearch(0, Math.max(...times)*n, times, n);
}

0개의 댓글