-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathSqrtX.java
More file actions
35 lines (30 loc) · 827 Bytes
/
SqrtX.java
File metadata and controls
35 lines (30 loc) · 827 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
package math;
/**
* Description: https://leetcode.com/problems/sqrtx
* Difficulty: Easy
* Time complexity: O(log n)
* Space complexity: O(1)
*/
public class SqrtX {
public int mySqrt(int x) {
if (x < 2) return x;
// 0 < sqrt(x) < x / 2
int left = 2;
int right = x / 2;
while (left <= right) {
int mid = left + (right - left) / 2;
if (mid > x / mid) {
right = mid - 1;
} else if (mid < x / mid) {
left = mid + 1;
} else {
// only works if sqrt(x) is an integer
return mid;
}
}
// we reached the BS out condition
// -> left > right
// -> right is the closest value to sqrt(x) rounded down
return right;
}
}