0069. Sqrt(x)
Easy | Binary Search | 28 ms (96.39%), 14 MB (97.73%)
Source: LeetCode - Sqrt(x) GitHub: Solution / Performance
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.
Note: You are not allowed to use any built-in exponent function or operator, such as pow(x, 0.5)
or x ** 0.5
.
Binary Search Problem Sorted array to find a minimum number that its power is larger than the input number.
Boundary / Search Space
Left (Minimum) = 1 (first version) Right (Maximum) = x (last element could be the answer)
Condition
While Loop = Left < Right Return = mid * mid == x
Return Value
Left - 1 (square root in integer type means to be smaller or equal to the original number)
Last updated
Was this helpful?