题目描述
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;
}
}