We are asked to implement the integer square root of a non-negative integer x.
That means returning the largest integer r such that r * r <= x.
Constraints:
0 <= x <= 2³¹ - 1
Key insight:
- The function is monotonic: if
mid * mid <= x, then all numbers ≤midare valid candidates. - This naturally suggests a binary search approach.
- Initialize search range:
left = 0,right = x. - While
left <= right:- Compute middle:
mid = left + (right - left) / 2. - Compare
mid * midwithx:- If equal, return
mid. - If smaller, move
left = mid + 1(search larger values). - If larger, move
right = mid - 1(search smaller values).
- If equal, return
- Compute middle:
- When the loop ends,
leftwill overshoot by one, so returnleft - 1.
- Use
long longwhen computingmid * midto avoid integer overflow. - Binary search guarantees finding the correct floor value.
- Returning
left - 1ensures correctness when no exact square root is found.
- Time:
O(log x)- Each iteration halves the search range.
- Space:
O(1)- Only a few variables are used.