Given a non-negative integer x, return the square root of x rounded down to the nearest integer. The returned integer should be non-negative as well.
You must not use any built-in exponent function or operator. For example, do not use pow(x, 0.5) or x ** 0.5.
Instead, use binary search over the candidate answers to find the largest integer r such that r * r <= x.
Function Signature
def my_sqrt(x: int) -> int:
Rules
-
Return the largest integer
r >= 0
such that
r * r <= x
. For a perfect square this is the exact root; otherwise it is the root rounded down.
Constraints
Examples
Input: x = 8
Output: 2
The square root of 8 is 2.82842..., which rounds down to 2. As a check, 2 * 2 = 4 is at most 8 and 3 * 3 = 9 is larger than 8.
Input: x = 16
Output: 4
The square root of 16 is exactly 4.
Input: x = 2147483647
Output: 46340
46340 * 46340 = 2147395600 does not exceed the input, while 46341 * 46341 = 2147488281 does, so 46340 is the largest valid root.