69. Sqrt(x)

Given a non-negative integer x, return the square root of x rounded down to the nearest integer. The returned integer should be non-negative as well.

My Solutions:

class Solution {
    public int mySqrt(int x) {
        if (x == 0 || x == 1) return x;
        int l = 1, r = x;
        while (l + 1 < r) {
            int mid = l + (r - l) / 2;
            if (mid == x / mid) return mid;
            else if (mid < x / mid) l = mid;
            else r = mid;
        }
        return l; // round down to the nearest integer --> only return l
    }
}

Last updated