Question

The code base version is an integer and start from 1 to n. One day, someone commit a bad version in the code case, so it caused itself and the following versions are all failed in the unit tests.
You can determine whether a version is bad by the following interface:

Java:
public VersionControl {
}
C++:
class VersionControl {
public:
};
Python:
class VersionControl:

Note
You should call isBadVersion as few as possible.

Please read the annotation in code area to get the correct way to call isBadVersion in different language. For example, Java is VersionControl.isBadVersion.

Example
Given n=5

return 4 is the first bad version

Challenge
Do not call isBadVersion exceed O(logn) times.


Java

/**
* public class VersionControl {
*     public static boolean isBadVersion(int k);
* }
* you can use VersionControl.isBadVersion(k) to judge wether
* the kth code version is bad or not.
*/
class Solution {
/**
* @param n: An integers.
* @return: An integer which is the first bad version.
*/
if (n == 0) {
return -1;
}

int start = 1, end = n, mid;
while (start + 1 < end) {
mid = start + (end - start)/2;
start = mid;
} else {
end = mid;
}
}

return start;
} else if (VersionControl.isBadVersion(end) == true) {
return end;
} else {
}
}
}


C++

/**
* class VersionControl {
*     public:
* }
* you can use VersionControl::isBadVersion(k) to judge wether
* the kth code version is bad or not.
*/
class Solution {
public:
/**
* @param n: An integers.
* @return: An integer which is the first bad version.
*/
if (n < 1) {
return -1;
}

int start = 1;
int end = n;
int mid;
while (start + 1 < end) {
mid = start + (end - start) / 2;
end = mid;
} else {
start = mid;
}
}

return start;
return end;
}

return -1;  // find no bad version
}
};


Python

#class VersionControl:
#    @classmethod
#        # Run unit tests to check whether verison id is a bad version
#        # return true if unit tests passed else false.
# You can use VersionControl.isBadVersion(10) to check whether version 10 is a
class Solution:
"""
@param n: An integers.
@return: An integer which is the first bad version.
"""
if n < 1:
return -1

start, end = 1, n
while start + 1 < end:
mid = start + (end - start) / 2
end = mid
else:
start = mid

return start
return end

return -1


Leetcode版題解

// Forward declaration of isBadVersion API.

class Solution {
public:
int lo = 0, hi = n;
while(lo < hi){
int m = lo + (hi - lo)/2;
return m+1;