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.
/**
* 使用二分查找法
* 任何一个数的算术平方根绝对不会大于这个数的的一半(显然)
* 所以二分查找初始设为left=1,right=x/2
* 退出条件为:mid*mid<=x && (mid+1)*(mid+1)>x
*/
public class SqrtSolution {
public int mySqrt(int x) {
int left = 1;
int right = x / 2;
while (right >= left) {
int mid = (left + right) / 2;
//乘法变为除法,防止溢出
if (mid > x / mid) {
right = mid - 1;
} else if (mid <= x / mid && (mid + 1) > x / (mid + 1)) {
return mid;
} else {
left = mid + 1;
}
}
return x;
}
}