Binary search solution in C log(n)


  • 0
    M
    int mySqrt(int x) {
        int mid;
        int l = 1;
        int r = x;
        if(x==0) return 0;
        
        while(1)
        {
            mid = l + (r-l)/2;
            if(mid > x/mid)
            {
                r = mid - 1;
            }
            else
            {
                if(mid + 1 > x/ (mid+1)) return mid;
                l = mid + 1;
            }
        }
    }
    

Log in to reply
 

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