이분탐색
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 함수가 호출될 때 두번째 인수의 크기가 너무 커지면 >> 연산으로 원하는 결과가 나오지 않을 수 있고 몇몇 테스트 케이스에서 에러가 발생하게 된다.
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);
}