SQRT(x)功能实施;$(i ^ 2 \ leq x)\ land((i + 1)^ 2> x)$ chine?
-
29-09-2020 - |
题
最近我正在研究一个 leetcode问题
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.
.
这里是一种解决方案,即除了一行之外,我真的很喜欢和理解。它使用二进制搜索来获取解决方案:
int mySqrt(int x) {
if (x == 0) return x;
int left = 1, right = INT_MAX, mid;
while(left < right) {
mid = left + (right - left)/2;
if (mid <= x / mid && (mid + 1) > x / (mid + 1)) {
return mid;
}
if (mid < x/mid) {
left = mid + 1;
} else { // mid > x/mid
right = mid;
}
}
return right;
}
.
概念问题是:为什么要给出特定数字,说 $ i $ , $$(i ^ 2 \ leq x)\ land((i + 1)^ 2> x)$$ 返回 $ i $ 是截断的 $ x $ 的整数表示?(上面的代码块返回相同条件,但重新排列不等式以避免整数溢出)
解决方案
我将两个不等式放在一起,因为可读性: $ i ^ 2 \ leq x <(i + 1)^ 2 $ 。
拍摄正数的正方形是单调功能。因此, $$ i ^ 2 \ leq x <(i + 1)^ 2 \意味着i \ leq | \ sqrt {x} |然后, $ | \ sqrt {x} | $ 显然是 $ i $ 。
不隶属于 cs.stackexchange