69 - Sqrt(x)

来源:互联网 发布:剑三喵太捏脸数据 编辑:程序博客网 时间:2024/05/01 04:06

Implement int sqrt(int x).

Compute and return the square root of x.

Subscribe to see which companies asked this question

思路分析:

牛顿迭代法求解平方根。

此时,令f(x) = x^2 - a, 此时迭代格式为:


class Solution {public:    int sqrt(int x) {        // Start typing your C/C++ solution below        // DO NOT write int main() function        if (x==0) {return 0;}        if (x==1) {return 1;}               double x0 = 1;        double x1;        while (true){            x1 = (x0+ x/x0)/2;            if (abs(x1-x0)<1){return x1;}            x0=x1;        }             }};


0 0