sqrt(x)

来源:互联网 发布:风云纯网络防火墙 编辑:程序博客网 时间:2024/05/16 08:36

题目

Implement int sqrt(int x).

Compute and return the square root of x.

思路

可以用牛顿迭代法求平方根,Xk+1 = 1/2 * ( Xk + n/Xk ) ;

要注意,函数的输入和返回都是 int 型。


代码

class Solution {public:    int sqrt(int x) {        // Start typing your C/C++ solution below        // DO NOT write int main() function        double s = x;        double t = 1.0;        while(abs(int(s)-int(t))>0)        {            s = t;            t = 0.5*(s+double(x)/s);        }        return int(t);    }};


原创粉丝点击