• why can't we use , mid = (left+ right)/2 instead of above expression ?

• because "Unless you are using a language that does not overflow such as Python, left + rightleft+right could overflow."

• Same question here, why mid = (left+ right)/2 doesn't work?, @mscho147 could you please explain why left+right could overflow?

• Because situation like : (left+right) > INT_MAX, causing overflow

• @benyin Thanks!

• This post is deleted!

• If you want to do (left + right)/2, you have to cast in order to make the overflow work correct. In that case you would have to do:

``````mid = (int)(((long)left + right)/2);
``````

Clearly this is more verbose and error prone than simply doing left + (right-left)/2;

• @webmihir long L,R; there only one cast when calling isbadversion, and second when returning.

• Why is there not an accepted answer that solves this recursively?

• Can someone please explain to me why sometimes we use the terminating condition `while(start<end)` while some other times we use `while(start<=end)` . I am not able to grok this thing and it causes too much confusion and frustration.An explanation to this would be very highly appreciated. Thank you!

• @thalaivva
(start == end) means that it already have find out the first bad version and it dosen't need to check.

• @thalaivva were you able to figure it out eventually?

I am having the same doubt.

• @alagram @thalaivva if the while statement runs when left == right, it falls into an infinite loop as it results always if (isBadVersion(mid)) { right = mid; }. So to exit the while statement, it should be left < right so it can exit when it is left == right.

• Why when I use mid = (left + right) / 2 time limit exceeded is returned and when we use mid = left + (right - left) / 2 it works?

• @idomiralin if the sum of left + right is very big or overflow, you may have trouble with some test cases I guess?

• @cognos yes, you're right.

• why not just start from the lasted version - 1? since the bad version is likely to be near the latest version

• @sotondolphin There is no guarantee where the first bad version will be, for all we know the first element of the list could be bad! Doing a binary search allows us to close in on the precise location of the error -- if the error is really towards the end, we will determine that very quickly.

• To my uter surprise low+(high-low)>>1 is giving TLE and low+(high-low)/2 is getting AC. How is this possible?
We know bit manipulation is faster than arithmetic calculations or I am wrong in my assumption?

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.