Sqrt(x)
Given a non-negative integer xx
You must not use any built-in exponent function or operator.
- For example, do not use
in c++ orpow(x, 0.5) in python.x ** 0.5
Example 1
Output: 2
Explanation: The square root of 4 is 2, so we return 2.
Example 2
Output: 2
Explanation: The square root of 8 is 2.82842..., and since we round it down to the nearest integer, 2 is returned.
Constraints:
1 <= nums.length <= 231-1
Contents
Solution 1 - Using binary search
In the problem statement, it is mentioned that we cannot use any inbuilt functions, and in case if the answer has decimals we will need to round it down to nearest integer.
so in this approach, what we will do is using 1 and x as left and right boundaries,
we will apply
We will compute the midsquare
-
If the
value is equal tosquare , then return thex value.mid -
If the
value is greater than x, this means that the target lies on left side, so we will updatesquare value toright .mid-1 -
If the
value is less than x, this means that the target lies on right side, so we will updatesquare value toleft .mid+1
If the answer is not found, we will return rightsquarexmid-1
public class Sqrt {
static int mySqrt(int x) {
int left = 1;
int right = x;
while(left <= right) {
int mid = left + (right - left) /2;
long square = (long)mid * mid;
if(square == x) {
return mid;
} else if(square > x) {
right = mid -1;
} else {
left = mid+1;
}
}
return right;
}
public static void main(String[] args) {
System.out.println(mySqrt(4));
System.out.println(mySqrt(8));
System.out.println(mySqrt(2147395599));
}
}
Complexity Analysis:
Time complexity: Above code runs in O(log n) time where nx
Space complexity: O(1).
Above implementations source code can be found at