[LeetCode] Sqrt(x)
Implement int sqrt(int x)
.
Compute and return the square root of x.
x is guaranteed to be a non-negative integer.
Example 1:
Input: 4 Output: 2
Example 2:
Input: 8 Output: 2 Explanation: The square root of 8 is 2.82842..., and since we want to return an integer, the decimal part will be truncated.
编写Sqrt(x)函数
使用二分搜索来查值进行平分计算。
class Solution { public: int mySqrt(int x) { int left = 0, right = x; while (left <= right) { long long mid = left + (right - left) / 2; if (pow(mid, 2) > x) { right = mid - 1; } else { if (pow(mid + 1, 2) > x) return mid; left = mid + 1; } } } }; // 22 ms