```
// Forward declaration of isBadVersion API.
bool isBadVersion(int version);
class Solution {
public:
int firstBadVersion(int n)
{
if(n == 1) return 1;
int start_idx = 1, end_idx = n;
while(start_idx < end_idx)
{
// !!!!!!!! avoid overflow ///////////////////
int mid = start_idx + (end_idx - start_idx)/2;
if( isBadVersion(mid) ) end_idx = mid;
else start_idx = mid+1;
}
return start_idx;
}
};
```