Sqrt(x) 解答

时间:2022-11-02 19:33:28

Question

Implement int sqrt(int x).

Compute and return the square root of x.

Solution 1 -- O(log n)

常规做法是用的binary search。注意这里mid一定要是long类型,否则mid * mid会溢出。

 public class Solution {
public int mySqrt(int x) {
// Use long instead of int
long start = 1, end = x, mid;
while (start + 1 < end) {
mid = (end - start) / 2 + start;
long tmp = mid * mid;
if (tmp == x) {
return (int) mid;
} else if (tmp < x) {
start = mid;
} else {
end = mid;
}
}
if (end * end <= x)
return (int) end;
return (int) start;
}
}

Solution 2 -- Constant Time

我们可以通过以下数学公式缩小问题规模:

Sqrt(x) 解答

因此,问题转换成如何求 log2N

注意到对于任何数,它的binary representation可以表示为Σ2i

所以 log2N 的取值范围为[i, i + 1] i 为最高位的位数。

因此我们就缩小了二分查找的范围。

 public class Solution {
public int mySqrt(int x) {
int num = x, digit = 0;
while (num > 0) {
num = num >> 1;
digit++;
}
int candidate1 = (int) Math.pow(2, 0.5 * digit);
int candidate2 = (int) Math.pow(2, 0.5 * (digit - 1));
long start = candidate2, end = candidate1, mid;
while (start + 1 < end) {
mid = (end - start) / 2 + start;
long tmp = mid * mid;
if (tmp == x)
return (int) mid;
if (tmp < x)
start = mid;
else
end = mid;
}
if (end * end <= x)
return (int) end;
return (int) start;
}
}