Integer Square Root with Error Checks
Problem statement
Return floor(sqrt(x)) when x is nonnegative. Return -1 when x is negative.
Do not use a library square-root function, and avoid overflow when comparing a candidate square with x.
Function
integerSqrt(x: int) → intExamples
Example 1
x = 8return = 2The square root is between 2 and 3, so its floor is 2.
Example 2
x = -4return = -1Negative input uses the documented sentinel.
Constraints
-2^31 <= x <= 2^31 - 1.