LeetCode每日一题:sqrtx

问题描述

Implementint sqrt(int x).
Compute and return the square root of x.

问题分析

这道题目直接调用Math.sqrt(x)也可以AC,但是我们最好用二分查找或者牛顿迭代法来进行查找。
牛顿迭代法是通过切线来确定根的位置,通过无限趋近的极限思想来找平方根,证明省略,我们直接使用结论。

x[i+1]=x[i]/2+n/(2*x[i]);
当x[i+1]趋近于x[i]时,x[i]即为要求的解

代码实现

public int sqrt(int x) {
        if (x == 0) return 0;
        double pre = 0;
        double cur = 1;
        while (Math.abs(cur - pre) > 0.001) {
            pre = cur;
            cur = pre / 2 + x / (2 * pre);
        }
        return (int) cur;
    }

你可能感兴趣的:(LeetCode每日一题:sqrtx)