(start+end)/2 vs start+(end-start)/2

  • 0

    My question is, when getting the middle value, there seems a difference between (start+end)/2 and start + (end-start)/2.

    I found that the first method will exceed time limit, while the second doesn't. I am really confused why this happens. Anyone has an explanation about this? Thanks!

    The code is pasted below:

    public class Solution extends GuessGame {
    public int guessNumber(int n) {

        int start = 1;
        int end = n;
            //int mid = (start+end)/2;
            int mid = start + (end-start)/2;
            int result = guess(mid);
            if(result == 0){
                return mid;
            }else if(result==-1){
                end = mid-1;
                start = mid+1;
        return -1;


  • 2
    int mid = (start + end) / 2; -> can suffer from overflow

  • 0

    Indeed. Thx!

Log in to reply

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