// Forward declaration of isBadVersion API.
bool isBadVersion(int version);
class Solution {
public:
int firstBadVersion(int n) {
return binarySearch(1,n);
}
int binarySearch(int a, int b){
if(a==b) {
if(isBadVersion(a)) return a;
else return 0;
}
if(isBadVersion(a+(b-a)/2)){
return binarySearch(a,a+(b-a)/2);
}else{
return binarySearch(a+(b-a)/2+1,b);
}
}
};
注意一点在写二分查找的时候我们要用a+(b-a)/2来写,两侧边界也要符合习惯,否则后期会溢出