Sqrt(x)
应该找一个平方比x小的数,end比start大,如果end的平方就满足标准 那么start肯定满足标准,所以先check end
犯错:最后check应该先判断x/ start >= start,因为找一个平方比x小的最大值
Implement int sqrt(int x)
.
Compute and return the square root of x, where x is guaranteed to be a non-negative integer.
Since the return type is an integer, the decimal digits are truncated and only the integer part of the result is returned.
Example 1:
Input: 4
Output: 2
Example 2:
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;
}
}
Last updated