# O(lgN) simple Java solution

• The binary search code:

``````public int firstBadVersion(int n) {
int start = 1, end = n;
while (start < end) {
int mid = start + (end-start) / 2;
if (!isBadVersion(mid)) start = mid + 1;
else end = mid;
}
return start;
}``````

• `````` public int firstBadVersion(int n) {
return binarySearch(1,n);
}

public int binarySearch(int start, int end) {
long startLong = start;
long endLong = end;
Long middleLong = (startLong + endLong) / 2;
int middle = middleLong.intValue();

return middle;
}

return binarySearch(start,middle);
} else {
return middle+1;
}

return binarySearch(middle + 1, end);
}
}``````

• if I use 'int mid = (left + right)/2;' in the while sentance,the program will apear error 'Time Limit Exceeded'. Why? Thank you!

• Hi, lixiao, if left and right are both very large, their sum will exceed integer limit

• Greate! I encountered the same issue. And your method works well. Thanks.

• Very nice explanation, I am stuck at strange RunTime errors, so this is the issue

• very simple and concise

• I think there is no need to use long.We can use "int mid = start + (end-start) / 2;" to solve the problem.

• why can't use mid = (start+end) / 2?

• I think they are the same.

Edit: my above comment is WRONG! My understanding is that `start + (end-start) / 2` can avoid possible overflow, for example `start = 2^20` and `end = 2^30`.

• if start and end are both very large, their sum will exceed integer limit

• thanks, i see!

• What I learnt from a Google software engineer is that this kind of possible overflow will not affect the interview because overflow is `NOT` the focus of this test problem. So don't pay too much attention to it if you are not so used to considering overflow.

• What I learnt from a Google software engineer is that `this kind of possible overflow will not affect your interview performance` because overflow is NOT the focus of this test problem. So don't worry too much even if you are not so used to considering overflow. However, if the test problem is on overflow, then you have to be careful not to miss it.

• shame on those giving out "random" down votes without any explanation. If you disagree, please leave your thoughts here so others can possibly learn from you.

• how about the n is only 1 and 1 is not bad version?

• the problem said there must be a bad version

• @lixiaolun overflow issue.

• Recommended way to avoid overflow in Java when calculating mid is to use the unsigned right shift operation (>>>):

``````int mid = (from + to) >>> 1;
``````

• Another option to avoid overflow : subtract

``````         int cursor = n, good = 0, bad = n;
while(bad - good > 1) {
} else {
good = cursor;
}
}

``````

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