Sqrt(x)

Easy#69search the answer

You get a non-negative integer x. Return its square root rounded down, without a built-in power or root function. Our example: x = 20 — the answer is 4: 4 · 4 = 16 fits under 20, 5 · 5 = 25 does not.

input
x: a non-negative integer.
returns
The square root of x rounded down to an integer. LeetCode wants it without a built-in power function or operator such as pow(x, 0.5) or x ** 0.5.
constraints
  • 0 ≤ x ≤ 2³¹ − 1
our 12 tests keep to them
examples
Open a test in the tests panel: it shows the input and the expected answer.
/**
 * @param {number} x
 * @return {number}
 */
function mySqrt(x) {

}
Ctrl ↵
format
reset

saved in this browser

12 tests · limit 3 s

Stuck?

See the solution run step by step on our example, then why it works and its complexity.

Watch the walkthrough →

Next: more binary search problems

Pattern “Binary search” →

The problem and its statement belong to LeetCode. Here are our own retelling, example and solution. Patterns Hero is not affiliated with LeetCode.