题目:
Implement int sqrt(int x)
.
Compute and return the square root of x.
求平方根,用二分法,时间复杂度为O(lgN)代码:
public class Solution {
public int mySqrt(int x) {
if(x<2)return x;
int left =1,right=x/2,last_mid=0;
while(left<=right)
{
int mid= left+(right-left)/2;
if(x/mid<mid)
{
right=mid-1;
// last_mid=mid;
}
else if(x/mid>mid)
{
left=mid+1;
//如果未能找到相等的,去小于该值的平方根
last_mid=mid;
}
else
{
return mid;
}
}
return last_mid;
}
}