# The is_bad_version API is already defined for you.
# @param {Integer} version
# @return {boolean} whether the version is bad
# def is_bad_version(version):

# @param {Integer} n
# @return {Integer}
def first_bad_version(n)
    left = 1
    right = n

    while left < right do
        mid = (left + right).div(2)

        if is_bad_version(mid) then
            right = mid
        else
            left = mid + 1
        end
    end

    return left
end

RSpec.describe "first_bad_version" do
    it "n = 5, bad = 4" do
        def is_bad_version(n)
            return n >= 4
        end
        expect(first_bad_version(5)).to eq(4)
    end

    it "n = 1, bad = 1" do
        def is_bad_version(n)
            return n >= 1
        end
        expect(first_bad_version(1)).to eq(1)
    end

    it "n = 1000000, bad = 76192" do
        def is_bad_version(n)
            return n >= 76192
        end
        expect(first_bad_version(1000000)).to eq(76192)
    end
end