math
binary-search
Given a non-negative integer x, return the integer square root of x — the largest integer r such that r * r <= x. The fractional part is truncated (rounded down), and you must not use any built-in square-root function.
Input / output
- Input:
x: integer - Output:
floor(sqrt(x))
Examples
x = 4returns2.x = 8returns2(sqrt(8) = 2.828..., truncated to2).x = 0returns0.
Constraints
0 <= x <= 2,147,483,647
Follow-up
Binary search gives O(log x). Guard the midpoint test against overflow (in fixed-width languages) by comparing mid to x / mid instead of computing mid * mid. Could Newton's method converge faster?
Examples
Example 1
Input: x = 4
Output: 2
Example 2
Input: x = 8
Output: 2
Example 3
Input: x = 0
Output: 0
🔒 5 hidden
Running will execute all 8 cases, including 5 hidden ones.