Implement int sqrt(int x).
Compute and return the square root of x.
求一个数的平方根,比较容易的方法是采用二分法不断逼近,不过比较有意思的是牛顿迭代法,这里有一个比较清晰的解释。
下面给出简单的实现:
class Solution {
public:
int mySqrt(int x) {
if (x == 0) return 0;
double m = x;
double n = m/2;
while(m/n - n > 0.000001 || n-m/n >0.000001){
n = (n + m/n)/2;
}
return n;
}
};