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:
Input: x = 4
Output: 2Example 2:
Input: x = 8
Output: 2
Explanation: The square root of 8 is 2.82842..., and since the decimal part is truncated, 2 is returned.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
func mySqrt(x int) int {
l, r := 0, x/2+1
for l+1 < r {
mid := l + (r-l)/2
square := mid * mid
if square == x {
return mid
}
if square < x {
l = mid
} else {
r = mid
}
}
if r*r <= x {
return r
}
return l
}Last updated
Was this helpful?