【题目】
Implement int
sqrt(int x).
Compute and return the square root of x.
【解析】
求平方根,注意因为是int型,所以只用求到整数位即可。
【代码】
public int mySqrt(int x) {
if(x==0) return 0;
int left=1,right=x;
while(left<right){
int m=left+(right-left)/2;
if(x/m>=m&&x/(m+1)<(m+1))
return m;
else if(x/m<m)
right=m-1;
else
left=m+1;
}
return left;
}
本文介绍了一种求解整数平方根的有效算法,并通过一个具体的Java方法进行了实现。该算法利用二分查找的方式,在整数范围内精确找到目标值的平方根。

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



