#278

First Bad Version

pupil · 495 · lc easy +27 · verified · 46.9% accepted · 9,009 likes · top 31%

play →

Description

You are managing a versioned product. A defect was introduced at some point, and every version after it is also defective.

Given n versions numbered [1, 2, ..., n], use the API bool isBadVersion(version) to find the earliest defective version while minimizing the number of API calls.

Example 1:

Input: n = 5, bad = 4
Output: 4
Explanation:
call isBadVersion(3) -> false
call isBadVersion(5) -> true
call isBadVersion(4) -> true
Then 4 is the first bad version.

Example 2:

Input: n = 1, bad = 1
Output: 1

Code

1
2
3
4
5
6