LeetCode 69 - Sqrt(x)

Implement int sqrt(int x).

Compute and return the square root of x.

Solution 1:

Binary Search. m*m <= x < (m+1)*(m+1)

public int sqrt(int x) {
    if(x <= 1) return x;
    int l = 1, h = x / 2 + 1;
    while(l <= h) {
        int m = (l + h) / 2;
        if(x/m>=m && x/(m+1)<m+1) {
            return m;
        } else if(x/m < m) {
            h = m-1;
        } else {
            l = m+1;
        } 
    }
    return l;
}
 

Solution 2:

Also Binary Search. m*m <= x < (m+1)*(m+1)

public int sqrt(int x) {
    if(x <= 1) return x;
    int l = 1, h = x / 2 + 1;
    while(l <= h) {
        int m = (l + h) / 2;
        if(x/m < m) {
            h = m-1;
        } else if(x/m > m){
            l = m+1;
        } else {
            return m;
        }
    }
    return (l+h)/2;
}

 

Solution 3:

Newton's Method.

public int sqrt(int x) {
    double eps = 0.001;
    double last = x / 2.0;
    do {
        last = (last + x / last) / 2.0;
    } while(last*last - x > eps);
    return (int)last;
}

 

你可能感兴趣的:(LeetCode 69 - Sqrt(x))