Sqrt(x)
Input: 4
Output: 2Input: 8
Output: 2
Explanation: The square root of 8 is 2.82842..., and since
the decimal part is truncated, 2 is returned.class Solution {
public int mySqrt(int x) {
if(x == 0)
return 0;
//binary search
int start = 1, end = x;
while(start + 1 < end){
int mid = start + (end - start)/2;
if(x / mid == mid){
return mid;
}
else if(x / mid > mid)
start = mid;
else
end = mid;
}
//应该先check end
if(x/ start >= start){
return start;
}
else
return end;
}
}Last updated