Back to Dashboard
Sqrt
MediumProblem Statement
Given 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. For example, do not use pow(x, 0.5) in C++ or x ** 0.5 in Python.
Examples
Example 1:
- Input:
x = 4 - Output:
2
Example 2:
- Input:
x = 8 - Output:
2
Approach 1: Binary Search
O(logn)
O(1)
class Solution {
public int mySqrt(int x) {
if (x < 2) {
return x;
}
var l = 1;
var r = x / 2;
while (l <= r) {
int mid = l + (r - l) / 2;
long prod = (long) mid * mid;
if (prod == x) {
return mid;
} else if (prod > x) {
r = mid - 1;
} else {
l = mid + 1;
}
}
return r;
}
}