Implement int sqrt(int x)
.
Compute and return the square root of x.
Java
public class Solution {
public int mySqrt(int x) {
if(x == 0) return 0;
int start = 1;
int end = x/2 + 1;
while(end >= start)
{
int s = (start + end)/2;
if(s <= x/s && (s+1) >x/(s+1) ) return s;
else if(s < x/s) start = s + 1;
else end = s- 1;
}
return -1;
}
}
注意,之前使用s*s <=x && (s+1)*(s+1) > x会导致超时,time limit exceed