11.Sqrt(x) 解答

Description:

Implement int sqrt(int x).

Compute and return the square root of x.

 

解题思路:

  直接利用牛顿迭代法进行解答,数值阈为0.0001,代码如下

class Solution {
public:
  int mySqrt(int x) {
  double ans=x;
  double delta=0.0001;
  while(fabs(pow(ans,2)-x)>delta){
    ans=(ans+x/ans)/2;
    }
  return ans;
  }
};

posted @ 2017-05-17 00:45  legooooo  阅读(123)  评论(0编辑  收藏  举报