PS/LeetCode

LeetCode / Binary Search / 278번 / First Bad Version / JS

KimMinJun 2023. 4. 5. 16:13

< 문제 바로가기 >

 

First Bad Version - LeetCode

Can you solve this real interview question? First Bad Version - You are a product manager and currently leading a team to develop a new product. Unfortunately, the latest version of your product fails the quality check. Since each version is developed base

leetcode.com

 

< 문제 간단설명 >

나쁜 버전인지 판단해서 boolean 값으로 반환하는 api가 isBadVersion 라는 이름으로 주어진다.

만약 n번째 버전이 나쁜 버전이라면 그 후의 n+1번째 버전부터는 쭉 나쁜 버전이다.

isBadVersion을 이용해서 맨 처음 나오는 나쁜 버전이 몇 버전인지 찾는 문제이다.

 

/**
 * Definition for isBadVersion()
 * 
 * @param {integer} version number
 * @return {boolean} whether the version is bad
 * isBadVersion = function(version) {
 *     ...
 * };
 */

/**
 * @param {function} isBadVersion()
 * @return {function}
 */
var solution = function(isBadVersion) {
    /**
     * @param {integer} n Total versions
     * @return {integer} The first bad version
     */
    return function(n) {
        let start = 0;
        let end = n;
        let version = 0;

        while(start <= end) {
            version = Math.floor((start + end) / 2);

            if(isBadVersion(version) === true) {
                end = version - 1;
            }
            else {
                start = version + 1;
            }
        }

        return start;
    };
};