您的位置:首页 > 其它

69 - Sqrt(x)

2016-03-09 11:22 330 查看
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;
        }
         
    }
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: