mySqrt

实现 int sqrt(int x) 函数。

计算并返回 x 的平方根,其中 x 是非负整数。

由于返回类型是整数,结果只保留整数的部分,小数部分将被舍去。

示例 1:

输入: 4
输出: 2

// 牛顿迭代, 或者使用exp(0.5 * ln(x))求解
class Solution {
    public int mySqrt(int x) {
        if(x == 0) return 0;
        double x0 = x;
        while(true){
            double x1 = 0.5 * (x0 + x/x0);
            if(Math.abs(x1 - x0) < 1e-7){
                break;
            }
            x0 = x1;
        }
        return (int)(x0);
    }
}
posted @ 2020-06-03 10:00  athony  阅读(180)  评论(0编辑  收藏  举报