题目描述
Implementint sqrt(int x).
Compute and return the square root ofx.
public class Solution {
public int sqrt(int x) {
if(x <= 0)
return 0;
int start=1;
int end=x/2+1;//end*end=x*x/4+x+1>x,提快速度;
while(start<end-1)
{
int mid=start+(end-start)/2;
if(mid == x/mid)//若用mid*mid 会越界。
return mid;
else if(mid > x/mid)
end=mid;
else
start=mid;
}
return start;
}
}
整数平方根算法实现

本文介绍了一种求解整数平方根的有效算法,并通过Java代码实现。该算法使用二分查找方法找到最接近目标值的平方根。适用于计算机科学中的数值计算场景。
2893

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



