Leetcode Sqrt(x)

OpenSoucre發表於2014-06-29

參考Babylonian method

x_0 \approx \sqrt{S}. (x0  越接近S的平方根越好)

x_{n+1} = \frac{1}{2} \left(x_n + \frac{S}{x_n}\right),

\sqrt S = \lim_{n \to \infty} x_n.

class Solution {
public:
    int sqrt(double x) {
        if(x == 0) return 0;
        double root = x/2, tolerance = 1.0e-2;
        do{
            root=(root+x/root)/2;
        }while(abs(root*root-x)>tolerance);
        return root;
    }
};

這題感覺題目有問題,返回的平方根竟然是整數,

另一種方法是是用二分搜尋

class Solution {
public:
    int sqrt(int x) {
        if(x < 2) return x;
        int left = 0, right = x;
        while(left <= right){
            int mid = (right+left)/2;
            if(mid < x/mid) left = mid+1;
            else if(x/mid < mid ) right = mid-1;
            else  return mid;
        }
        return right;
    }
};

如果題目要求的時浮點數可以考慮利用浮點數二分搜尋

相關文章