【题目】
Implement int sqrt(int x)
.
Compute and return the square root of x.
【题意】
实现x的平方根函数
【分析】
二分搜索
【实现】
<span style="font-size:18px;">public class Solution {
public int mySqrt(int x) {
double diff = 0.01; // 误差
int low = 0;
int high = x;
while(low <= high){
// 注意越界!所以用double来存
double mid = low + (high-low)/2;
if(Math.abs(mid*mid-x) <= diff){
return (int)mid;
}else if(x > mid*mid+diff){
low = (int)mid+1;
}else if(x < mid*mid-diff){
high = (int)mid-1;
}
}
// 当找不到时候,这是low,high指针已经交叉,取较小的,即high
return high;
}
}</span>
参考:上面的方法较为简短,但也存在一个缺点:因为是整数开方,向下取整,因此不需要浮点数那么高的精度,就可以计算出正确的整型结果返回了。因此可以尝试使用牛顿法进行开方,并且while语句内并不像一般计算浮点数开方那样保证误差精确到1E-9以下,而是设置为任意比1小的数字就可以了。
牛顿法开平方公式如下:
具体内容可参看维基百科页面:【平方根】条目下的【牛顿法】章节
https://zh.wikipedia.org/wiki/%E5%B9%B3%E6%96%B9%E6%A0%B9#.E7.89.9B.E9.A0.93.E6.B3.95
对于这个题目而言,下面这段Java代码执行时间更短:public class Solution { public int mySqrt(int x) {
if (x <= 0) {
return 0;
}
double result = 1.0;
while (Math.abs(result * result - x) > 0.9) {
result = (result + x / result) / 2.0;
}
return (int)result;
}
}