69. Sqrt(x)
LeetCode 69. Sqrt(x) [Medium]
- Implement
int sqrt(int x)
. - Compute and return the square root of x.
- x is guaranteed to be a non-negative integer.
Example 1
Input: 4
Output: 2
Example 2
Input: 8
Output: 2
Explanation: The square root of 8 is 2.82842...
Method 1
【O(log(n))time∣O(1)space】
package Leetcode.BinarySearch;
/**
* @author zhengstars
* @date 2024/01/14
*/
public class SqrtX {
public static int mySqrt(int x) {
if(x == 0 || x == 1){
return x;
}
int l = 1;
int r = x;
while (l <= r){
int mid = l + (r - l) / 2;
if(mid > x / mid){
r = mid - 1;
}else{
l = mid + 1;
}
}
return r;
}
public static void main(String[] args) {
System.out.println(mySqrt(8));
}
}
Enjoy Reading This Article?
Here are some more articles you might like to read next: