LeetCode 69. Sqrt(x)
参考网址:http://www.cnblogs.com/grandyang/p/4346413.html
Solution1:
class Solution {
public:
int mySqrt(int x) {
if (x <= 1) return x;
int left = 0, right = x;
while (left < right) {
int mid = (left + right) / 2;
if (x / mid >= mid) left = mid + 1;
else right = mid;
}
return right - 1;
}
};
Solution2:
牛顿法求方程的近似解,详细见维基链接。迭代公式如下:
针对此题可以构造函数 ,所以迭代公式是:
class Solution {
public:
int mySqrt(int x) {
if (x == 0) return 0;
double res = 1, pre = 0;
while (abs(res - pre) > 1e-6) {//设置迭代终止条件
pre = res;
res = (res + x / res) / 2;
}
return int(res);
}
};