[LeetCode] First Bad Version

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 };

 

posted @ 2015-09-07 21:52  jianchao-li  阅读(178)  评论(0编辑  收藏  举报