Just use binary search to find the first bad version. The code is as follows.
1 // Forward declaration of isBadVersion API. 2 bool isBadVersion(int version); 3 4 class Solution { 5 public: 6 int firstBadVersion(int n) { 7 int l = 1, r = n; 8 while (l < r) { 9 int m = l + (r - l) / 2;10 if (isBadVersion(m)) r = m;11 else l = m + 1;12 }13 return l;14 }15 };