69.Sqrt(x)
题意: 实现 int sqrt(int x), 返回根号下x。
Implement int sqrt(int x).
Compute and return the square root of x.
我的思路: 用折半查找的方法。
public int mySqrt(int x) {
int first = 1;
int last = x;
int result = 1;
if(x == 0){
return 0;
}
while(first <= last){
int mid = (first + last) / 2;
if (mid <= x / mid) { //if(mid * mid <= x) 用这个在LeetCode上运行就会超时
first = mid + 1;
result = mid;
}
else{
last = mid -1;
}
}
return result;
}
第二种方法: 这是牛顿法,牛顿法的公式推导请看牛顿迭代法求平方根。在求解高次方程时的一种无限逼近的方法,其关键思想是:切线是曲线的近似逼近。
public int mySqrt2(int x) {
long r = x;
while (r*r > x)
r = (r + x/r) / 2;
return (int) r;
}
本文介绍了解决LeetCode上的69.Sqrt(x)问题的两种方法:一种是使用折半查找的方式,另一种是采用牛顿迭代法。这两种方法都能有效地找到指定整数的平方根。

692

被折叠的 条评论
为什么被折叠?



