Assumption, if no direct root, return the floor: x = 5, return 2.
这里要考虑如果m*m > Integer.MAX_VALUE的越界情况。所以我们不是比较m*m 和x的关系,而是比较x/m 和m的关系。还要注意除数为0的情况。
public int sqrt(int x) {
if (x < 0) {
return -1;
}
if (x == 0 || x == 1) {
return x;
}
int high = x;
int low = 1;
while (low <= high) {
int m = low + (high - low) / 2;
if (x/m >= m && x/(m+1) < (m+1)) {
<span style="white-space:pre"> </span>return m;
} if (x/m > m) {
<span style="white-space:pre"> </span>low = m+1;
} else {
<span style="white-space:pre"> </span>high = m-1;
}
}
return -1;
}