LeetCode - 69. x 的平方根

69. x 的平方根

class Solution {

    private static final Integer MAX_POW = 46340;

    /**
     * 牛顿迭代
     * f(x) = x^2 - n
     * 切线方程:f(x) = f(xi) + f’(xi)(x - xi)
     * xi+1 = xi - f(xi) / f'(xi)
     * xi+1 = xi - (xi^2 - n) / (2xi) = (xi + n / xi) / 2
     * @param x
     * @return
     */
    private int iteration(int x) {

        if (x == 0) {
            return 0;
        }

        double last = 0;
        double result = 1;

        while (result != last) {
            last = result;
            result = (result + x / result) / 2;
        }

        return (int) result;
    }

    /**
     * 二分
     * 求upperbound n 使得 n * n > x
     * 则 n - 1 为所求
     * @param x
     * @return
     */
    private int binary(int x) {
        if (MAX_POW * MAX_POW <= x) {
            return MAX_POW;
        }
        int l = 0;
        int size = 46340;
        while (size > 0) {
            int half = size >> 1;
            int m = l + half;
            int pow = m * m;
            if (pow <= x) {
                l = m + 1;
                size = size - half - 1;
            } else {
                size = half;
            }
        }
        return l - 1;
    }

    public int mySqrt(int x) {
        return binary(x);
    }
}


猜你喜欢

转载自blog.51cto.com/tianyiya/2172839