c++ binary search (O(lg(n)))


  • 0
    int mySqrt(int x) {
        int l = (x == 1) ? 1 : 0, r = x;
        while (l + 1 < r) {
            long long mid = (l + r) >> 1;
            if (mid * mid == x) return mid;
            else if (mid * mid > x) r = mid;
            else l = mid;
        }
        return l;
    }
    

Log in to reply
 

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