暴力解法:
class Solution {
public int mySqrt(int x) {
for(int i=1 ; ; i++){
if(x/i<i){
return i-1;
}
}
}
}
牛顿法:x*x = a可以转化为 x*x - a = 0。令 f(x)= x*x - a ,如果方程在Xi处有解,则在Xi附近(一定区域内)斜率从两侧向Xi收敛,在Xi处斜率为0。在循环内迭代求解Xk斜率K,并求出当前斜率下,f(x)曲线与x轴的交点X(k+1),再令Xk = X(k+1)继续下次迭代。最终曲线会收敛于Xi点,具体细节可以百度,然后列式求导。
class Solution {
public int mySqrt(int x) {
long a = x;
while(a*a>x){
a = (a+x/a)>>1;
}
return (int)a;
}
}