【题解】Leetcode 69 x的平方根
牛顿迭代法求多项式根即可
迭代公式为
x
i
+
1
=
x
i
−
f
(
x
i
)
f
′
(
x
i
)
x_{i + 1} = x_i - \frac{f(x_i)}{f'(x_i)}
xi+1=xi−f′(xi)f(xi)
class Solution {
public:
int mySqrt(int x) {
double ans = 1;
for(int i = 1 ; i <= 100 ; i ++){
ans = ans - (ans*ans - (double)x)/(2*ans);
}
return ans;
}
};