【题目】
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;
}