Description
Implement int sqrt(int x).
Compute and return the square root of x.
Solution
返回整型的平方根,可以二分查找0-x。当然,还可以用牛顿迭代法求平方根,可以到任意精度。
class Solution {
public:
int mySqrt(int x) {
double ne1=0,ne2=x;
while(abs(ne2-ne1)>0.1){
ne1=ne2;
ne2=(ne1+x/ne1)/2;//牛顿迭代法
}
return ne2;
}
};
推到下牛顿迭代法求平方根: