69. Sqrt(x)
LeetCode 69. Sqrt(x)
Description
Given a non-negative integer x
, compute and return the square root of x
.
Since the return type is an integer, the decimal digits are truncated , and only the integer part of the result is returned.
Example 1:
Example 2:
Constraints:
0 <= x <= 2^31 - 1
Tags
Math, Binary Search
Solution
Perform Binary Search between 0
and x/2+1
(for x=1
). If x is not a perfect square number, i.e., we cannot find mid^2 == x
, we evaluate if the square of the right pointer is smaller than x
first, then check the left one. The reason is we have to find the maximum value whose square is no greater than x
.
Complexity
Time complexity:
Space complexity:
Code
Last updated
Was this helpful?