AlgoFrames

Square root floor

Standard · Write code · about 12 min

Given a non-negative integer x, return the square root of x rounded down: the largest integer k with k × k ≤ x.

Do not use a built-in square root or power function. The solution must run in O(log x) time.

Example 1

Input:

[8]

Output:

2

2 × 2 = 4 fits, 3 × 3 = 9 is too big.

Example 2

Input:

[16]

Output:

4

16 is a perfect square.

Constraints

  • 0 ≤ x ≤ 2,147,483,647

Learn the idea first: Binary search, a visual lesson.

More Binary search problems