题目
力扣
思路一 二分
从0到x二分查找满足条件的数。
代码一
class Solution {
public:
int mySqrt(int x) {
int l = 0, r = x;
while(l < r){
long mid = l + r >> 1;
// cout<<mid<<endl;
if(mid * mid <= x & 1) * (mid + 1) > x)
return mid;
else if(mid * mid <= x)
l = mid + 1;
else
r = mid - 1;
}
return l;
}
};
思路二 袖珍计算器算法
将函数变形,变成e的1/2*(lnx)。
代码二
class Solution {
public:
int mySqrt(int x) {
if(x == 0) return 0;
int ans = exp(0.5 * log(x));
return (long)(ans + 1) * (ans + 1) <= x ? ans + 1 : ans;
}
};
思路三 牛顿迭代法
找到函数y=x² - C的零点,C为x。初始化x0为x,作该点的切线,交x轴与一点,再从该点为x0,继续迭代,直到结果与答案接近。
代码三
class Solution {
public:
int mySqrt(int x) {
if(x == 0) return 0;
double x0 = x, c = x;
while(fabs(x0 * x0 - x) > 1e-4)
x0 = (x0 + c /x0) * 0.5;
return int(x0);
}
};