javabinary-searchsquare-root

Finding the square root of a number by using binary search


I tried using binary search to find the square root of an integer, but some how I couldn't pass a few test cases.

I was able to pass mySqrt(4) = 2, but I wasn't able to pass mySqrt(2147395599)

Any ideas on where I messed up?

public static int mySqrt(int x) {
        int left = 0;
        int right = x;

        if(x < 2){
            return x;
        }
        while(left < right){
            int mid = left + ((right - left) / 2);

            if(mid * mid == x){
                return mid;

            }
            else if(mid * mid < x){
                left = mid + 1;
            }
            else{
                right = mid; 
            }
        }
        return left - 1;
    }

Solution

  • Because mid * mid will overflow. You should use long to avoid the overflow. Then cast it back to int when you return the result.

    Try this code

    public static int mySqrt(int x) {
        long left = 0;
        long right = x;
    
        if(x < 2){
            return x;
        }
        while(left < right){
            long mid = left + ((right - left) / 2);
    
            if(mid * mid == x){
                return (int)mid;
    
            }
            else if(mid * mid < x){
                left = mid + 1;
            }
            else{
                right = mid;
            }
        }
        return (int)(left - 1);
    }