美文网首页
69. x 的平方根

69. x 的平方根

作者: 薄荷糖的味道_fb40 | 来源:发表于2019-04-27 11:39 被阅读0次

实现 int sqrt(int x) 函数。

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

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

示例 1:

输入: 4
输出: 2
示例 2:

输入: 8
输出: 2
说明: 8 的平方根是 2.82842..., 
     由于返回类型是整数,小数部分将被舍去。

思路:

https://www.cnblogs.com/grandyang/p/4346413.html这篇博客说得很清楚了,这里采用的是牛顿迭代法,和梯度下降有点类似,具体实现如下。

class Solution {
public:
    int mySqrt(int x) {
        if(x==0) return 0;
        double pre=0;
        double res=1;
        while(abs(pre-res)>1e-6)
        {
            pre=res;
            res=(res+x/res)/2;
        }
        return (int)res;
    }
};

相关文章

网友评论

      本文标题:69. x 的平方根

      本文链接:https://www.haomeiwen.com/subject/qpghnqtx.html