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;
}
};