278 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 based on the previous version, all the versions after a bad version are also bad.

Suppose you have n versions [1, 2, ..., n] and you want to find out the first bad one, which causes all the following ones to be bad.

You are given an API bool isBadVersion(version) which will return whether version is bad. Implement a function to find the first bad version. You should minimize the number of calls to the API.

Solution

// Forward declaration of isBadVersion API.
bool isBadVersion(int version);

class Solution {
public:
    int firstBadVersion(int n) {
        if ( isBadVersion(0) ) return 0;
        int l = 0, r = n, m;
        while ( true ) {
            m = (long(l)+long(r))/2;
            if ( not isBadVersion(m-1) and isBadVersion(m) ) return m;
            if ( isBadVersion(m-1) ) r = m-1;
            else l = m+1;
        }
        return 0;
    }
};

Notes
Overflow, overflow, overflow.
Be very careful when adding two numbers to gether. Use long to avoid it/

results matching ""

    No results matching ""