Here is the implementation:
function firstBadVersion(n):
left = 1
right = n
while left < right:
mid = left + (right - left) / 2
if isBadVersion(mid):
right = mid
else:
left = mid + 1
return left
Note: use left + (right - left) / 2 instead of (left + right) / 2 to avoid integer overflow. This runs in time with space (excluding input).