【分治】LeetCode 69. Sqrt(x)

LeetCode 69. Sqrt(x)

参考网址:http://www.cnblogs.com/grandyang/p/4346413.html
Solution1:

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

Solution2:
牛顿法求方程的近似解,详细见维基链接。迭代公式如下:

x n + 1 = x n f ( x n ) f ( x n )

针对此题可以构造函数 f ( x ) = x 2 n , f ( x ) = 2 x ,所以迭代公式是:
x n + 1 = x n 2 + n 2 x n

class Solution {
public:
    int mySqrt(int x) {
        if (x == 0) return 0;
        double res = 1, pre = 0;
        while (abs(res - pre) > 1e-6) {//设置迭代终止条件
            pre = res;
            res = (res + x / res) / 2;
        }
        return int(res);
    }
};

猜你喜欢

转载自blog.csdn.net/allenlzcoder/article/details/81177114