All problemsBack
Sqrt(x)
easyGiven 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.
Test Cases
Copy an input into themain harness and Run to verifyInput
x = 4Expected Output
2Input
x = 8Expected Output
2Explanation: The square root of 8 is 2.828..., and rounding down gives 2.
Constraints
- 0 <= x <= 2^31 - 1
Hints
Hint 1 — click to reveal
The answer lies somewhere in [0, x] — and that range is sorted with respect to 'is mid*mid <= x'.
Hint 2 — click to reveal
Use long for the multiplication, or compare with division, to avoid 32-bit overflow.
Java Compiler
Powered by OneCompiler. Starter code loads automatically — edit and hit Run.