#include <leetcode/utils.h>
#include <stdbool.h>

#define BAD 1000000000

[[gnu::__always_inline__]] inline bool isBadVersion(int version)
{
    return version >= BAD;
}

#ifdef V1
int firstBadVersion(int n)
{
    if (isBadVersion(n) == false)
        return n + 1;
    return firstBadVersion(n - 1);
}
#else
int firstBadVersion(int n)
{
    int i = 0, j = n;

    while (1)
    {
        if (!isBadVersion((j - i) / 4) && isBadVersion(j / 2))
            i = (j - i) / 4, j /= 2;
        else
            break;
    }

    for (; i <= n && j > 0; i++, j--)
    {
        if (isBadVersion(i))
            return i;
        if (!isBadVersion(j))
            return j + 1;
    }

    return i;
}
#endif
int main()
{
    ASSERT(firstBadVersion(2000000000), BAD, fail);
    return 0;
fail:
    return -1;
}
