Given a non-negative integer
You must not use any built-in exponent function or operator.
- For example, do not use
pow(x, 0.5) in c++ orx ** 0.5 in python.
Output: 2
Explanation: The square root of 4 is 2, so we return 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
-
If the
square value is equal tox , then return themid value. -
If the
square value is greater than x, this means that the target lies on left side, so we will updateright value tomid-1 . -
If the
square value is less than x, this means that the target lies on right side, so we will updateleft value tomid+1 .
If the answer is not found, we will return
Complexity Analysis:
Time complexity: Above code runs in O(log n) time where
Space complexity: O(1).
Above implementations source code can be found at