Tuesday, September 8, 2015

[LeetCode] First Bad Version

The question can be found https://leetcode.com/problems/first-bad-version/

Note: if we use m = (e+s)/2, it might cause overflow.
// Forward declaration of isBadVersion API.
bool isBadVersion(int version);

class Solution {
    
public:
    int firstBadVersion(int n) {
        int s = 1;
        while(s < n)
        {
            int m = s + (n-s)/2;
            if(isBadVersion(m)) n = m;
            else s = m+1;
        }
        return s;
    }
};