Short Java solution


  • 0

    This problem can be solved using standard binary search.

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

  • 0

    Not sure about "easiest" but it's not the shortest.


  • 0

    Yeah, I agree. Of course much longer than yours.


Log in to reply
 

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