class Solution {
public int mySqrt(int x) {
if ( x == 0){
return 0;
}
int start = 1;
int end = x;
while (start < end){
int mid = start + (end - start)/ 2;
if( mid <= x / mid && (mid+1) > x / (mid+1)){
return mid;
}else if( mid > x/mid){
end = mid; //
}else{
start = mid;
}
}
return start;
}
}
5
1 5
Mid = 3
9 > 5
Right = 3
Left = 1
Mid = 2
注意这个退出条件 , 和其他 二分不太一样,
if( mid <= x / mid && (mid+1) > x / (mid+1)){
return mid;
if( mid * mid <= x && (mid+1) * (mid+1) > x ), 这个乘法如果数很大,容易 overflow
0 8
4
16 > 8
Right = 4
Mid = 2
Left = 0
2 * 2 < 8, 3 * 3 > 8
4. 8. 9
2. x. 3
Return 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.