> For the complete documentation index, see [llms.txt](https://shangan.gitbook.io/algorithm/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://shangan.gitbook.io/algorithm/he-xin-suan-fa-200-ti/untitled-3/first-bad-version.md).

# First Bad Version

{% tabs %}
{% tab title="Java" %}

```java
class Solution {
    /**
     * @param n: An integers.
     * @return: An integer which is the first bad version.
     */
    public int findFirstBadVersion(int n) {
        int start = 1, end = n;
        while (start + 1 < end) {
            int mid = start + (end - start) / 2;
            if (SVNRepo.isBadVersion(mid)) {
                end = mid;
            } else {
                start = mid;
            }
        }
            
        if (SVNRepo.isBadVersion(start)) {
            return start;
        }
        return end;
    }
}

```

{% endtab %}

{% tab title="Python" %}

```python
class Solution(object):
    def firstBadVersion(self, n):
        """
        :type n: int
        :rtype: int
        """
        l,r = 0, n
        while l <=r:
            m = (l+r)//2
			# we find the target:
            if isBadVersion(m-1) == False and isBadVersion(m)== True:
                return m
			# we didn't find the target, we eleminate the half that the target cannot lie
            else:
                if isBadVersion(m) == False:
                    l = m +1
                else:
                    r = m -1
        return -1
```

{% endtab %}

{% tab title="JavaScript" %}

```javascript
var solution = function(isBadVersion) {
    /**
     * @param {integer} n Total versions
     * @return {integer} The first bad version
     */
    return function(n) {
        let left = 1;
        let right = n;
        let mid;
        while (left + 1 < right) {
            mid = (left + right) / 2 >>> 0;
            if (isBadVersion(mid)) {
                right = mid;
            } else {
                left = mid;
            }
        }
        return isBadVersion(left) ? left : right;
    };
};
```

{% endtab %}
{% endtabs %}

![](https://2784211123-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-M-ELB26IpzCEJWSDi0m%2F-M-ELbsic2B8wwsarT-C%2F-M-EMqc6UhBUlpM3zyHy%2F1580805867266.jpg?alt=media\&token=11a20b67-9e32-4c02-bf02-c405dac8ef0f)
