Since the return type is an integer, the decimal digits are truncated and only the integer part of the result is returned.
Input: 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;
}
}
class Solution {
public int mySqrt(int x) {
if(x < 2) return x;
int start = 0, end = x;
while(start <= end){
int mid = start+(end - start) /2;
if( x / mid == mid )
return mid;
else if(x / mid < mid) end = mid -1 ;
else
start = mid +1;
}
return end;
}
}